Skip to content

Commit

Permalink
Dynaming loading classes when not specified by the driver
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Austin committed Jul 19, 2023
1 parent 766499e commit 0ab6c32
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
29 changes: 24 additions & 5 deletions blockchain.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,28 @@ module.exports = class Blockchain {
throw new Error("The blockchain has already been initialized.");
}

// Storing details on classes.
if (blockClass) {
this.blockClass = blockClass;
} else {
this.blockClass = require('./block');
}
if (transactionClass) {
this.transactionClass = transactionClass;
} else {
this.transactionClass = require('./transaction');
}
if (clientClass) {
this.clientClass = clientClass;
} else {
this.clientClass = require('./client');
}
if (minerClass) {
this.minerClass = minerClass;
} else {
this.minerClass = require('./miner');
}

this.clients = [];
this.miners = [];
this.clientAddressMap = new Map();
Expand All @@ -218,15 +240,15 @@ module.exports = class Blockchain {
console.log(`Adding client ${clientCfg.name}`);
let client;
if (clientCfg.mining) {
client = new minerClass({
client = new this.minerClass({
name: clientCfg.name,
net: this.net,
miningRounds: clientCfg.miningRounds,
});
// Miners are stored as both miners and clients.
this.miners.push(client);
} else {
client = new clientClass({
client = new this.clientClass({
name: clientCfg.name,
net: this.net,
});
Expand All @@ -240,9 +262,6 @@ module.exports = class Blockchain {
this.initialBalances.set(client.address, clientCfg.amount);
});

// Storing details on classes.
this.blockClass = blockClass;
this.transactionClass = transactionClass;
}

/**
Expand Down
9 changes: 1 addition & 8 deletions driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,15 @@

let Blockchain = require('./blockchain.js');

// FIXME: Figure out how to remove these imports
let Block = require('./block.js');
let Client = require('./client.js');
// Used to create a miner outside of the blockchain constructor.
let Miner = require('./miner.js');
let Transaction = require('./transaction.js');

let FakeNet = require('./fake-net.js');

console.log("Starting simulation. This may take a moment...");

// Creating genesis block
let bc = Blockchain.createInstance({
blockClass: Block,
clientClass: Client,
minerClass: Miner,
transactionClass: Transaction,
clients: [
{name: 'Alice', amount: 233},
{name: 'Bob', amount: 99},
Expand Down

0 comments on commit 0ab6c32

Please sign in to comment.