Skip to content

Commit

Permalink
Printing out names of clients with balances, when a name is available
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Austin committed Jul 17, 2023
1 parent f9ae537 commit 76acce5
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
32 changes: 26 additions & 6 deletions blockchain.js
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ module.exports = class Blockchain {
*/
static createInstance(cfg) {
this.instance = new Blockchain(cfg);
this.makeGenesis();
this.instance.genesis = this.makeGenesis();
return this.instance;
}

Expand All @@ -192,7 +192,7 @@ module.exports = class Blockchain {
defaultTxFee = DEFAULT_TX_FEE,
confirmedDepth = CONFIRMED_DEPTH,
clients = [],
fakeNet,
net,
}) {

if (this.constructor.instance) {
Expand All @@ -201,8 +201,9 @@ module.exports = class Blockchain {

this.clients = [];
this.miners = [];
this.clientAddressMap = new Map();
this.clientNameMap = new Map();
this.fakeNet = fakeNet;
this.net = net;

this.powLeadingZeroes = powLeadingZeroes;
this.coinbaseReward = coinbaseReward;
Expand All @@ -219,21 +220,23 @@ module.exports = class Blockchain {
if (clientCfg.mining) {
client = new minerClass({
name: clientCfg.name,
net: this.fakeNet,
net: this.net,
miningRounds: clientCfg.miningRounds,
});
// Miners are stored as both miners and clients.
this.miners.push(client);
} else {
client = new clientClass({
name: clientCfg.name,
net: this.fakeNet,
net: this.net,
});
}

this.clientAddressMap.set(client.address, client);
if (client.name) this.clientNameMap.set(client.name, client);
this.clients.push(client);
this.fakeNet.register(client);
this.net.register(client);

this.initialBalances.set(client.address, clientCfg.amount);
});

Expand Down Expand Up @@ -313,4 +316,21 @@ module.exports = class Blockchain {
});
return clients;
}

register(...clients) {
clients.forEach((client) => {
this.clientAddressMap.set(client.address, client);
if (client.name) this.clientNameMap.set(client.name, client);
client.net = this.net;
this.net.register(client);
});
}

getClientName(address) {
if (!this.clientAddressMap.has(address)) {
return;
}
let client = this.clientAddressMap.get(address);
return client.name;
}
};
8 changes: 7 additions & 1 deletion client.js
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,15 @@ module.exports = class Client extends EventEmitter {
* according to the client's own perspective of the network.
*/
showAllBalances() {
let bc = Blockchain.getInstance();
this.log("Showing balances:");
for (let [id,balance] of this.lastConfirmedBlock.balances) {
console.log(` ${id}: ${balance}`);
let name = bc.getClientName(id);
if (name) {
console.log(` ${id} (${name}): ${balance}`);
} else {
console.log(` ${id}: ${balance}`);
}
}
}

Expand Down

0 comments on commit 76acce5

Please sign in to comment.