├── visualization ├── requirements.txt ├── visualizers │ ├── base.py │ ├── pbft.py │ └── hotstuff.py ├── README.md ├── parsers │ ├── base.py │ ├── pbft.py │ └── hotstuff.py └── main.py ├── .gitignore ├── attacker ├── fail-stop.js ├── attacker-node.js ├── partitioner.js └── vmware-attacker │ ├── static-attacker.js │ └── adaptive-attacker.js ├── config.js ├── ba-algo ├── node.js ├── async-BA.js ├── hotstuff-NS.js ├── vmware-ba │ ├── vrf.js │ ├── basic.js │ └── adaptive.js ├── algorand.js ├── libraBFT.js ├── basic-hotstuff.js └── pbft.js ├── package.json ├── lib ├── logger.js └── fp.js ├── README.md ├── main.js ├── examples ├── lambdas.js └── views.js ├── validator └── audit_queue.js ├── network └── network.js └── simulator.js /visualization/requirements.txt: -------------------------------------------------------------------------------- 1 | plotly==5.5.0 -------------------------------------------------------------------------------- /visualization/visualizers/base.py: -------------------------------------------------------------------------------- 1 | class BaseVisualizer: 2 | def draw(): 3 | raise NotImplementedError() -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # directories 2 | log/ 3 | node_modules/ 4 | views/ 5 | experiments-log/ 6 | experiments/ 7 | 8 | # vim temp file 9 | *.swp 10 | 11 | # node.js file 12 | package-lock.json 13 | 14 | # python stuff 15 | __pycache__ 16 | -------------------------------------------------------------------------------- /attacker/fail-stop.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class Attacker { 4 | 5 | updateParam = () => false; 6 | attack = (packets) => packets; 7 | send() {} 8 | onTimeEvent() {} 9 | onMsgEvent() {} 10 | constructor() {} 11 | } 12 | module.exports = Attacker; -------------------------------------------------------------------------------- /config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | // node 3 | nodeNum: 16, 4 | byzantineNodeNum: 0, 5 | // BFT protocol specific param 6 | lambda: 3, 7 | protocol: 'hotstuff-NS', 8 | // network environment 9 | networkDelay: { 10 | mean: 0.25, 11 | std: 0.05, 12 | }, 13 | // close the log will run a lot faster 14 | logToFile: false, 15 | attacker: 'fail-stop', 16 | repeatTime: 100, 17 | }; 18 | -------------------------------------------------------------------------------- /attacker/attacker-node.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('../ba-algo/node'); 4 | 5 | class AttackerNode extends Node { 6 | 7 | constructor(nodeID, nodeNum, network, registerTimeEvent, onMsgEvent, onTimeEvent) { 8 | super(nodeID, nodeNum, network, registerTimeEvent) 9 | this.registerTimeEvent = registerTimeEvent; 10 | this.onMsgEvent = onMsgEvent; 11 | this.onTimeEvent = onTimeEvent; 12 | } 13 | } 14 | 15 | module.exports = AttackerNode; -------------------------------------------------------------------------------- /visualization/README.md: -------------------------------------------------------------------------------- 1 | # Visualization 2 | Show the network messages transmitted by each node, the view of all nodes, and the time when a consensus is reached. 3 | 4 | Note: Currently, only PBFT and HotStuff BFT are supported. 5 | 6 | ### Usage 7 | 1. Install the required packages as indicated by `requirements.txt`. 8 | 2. Use the BFT simulator in the parent directory to generate execution traces. They will be located in the `log/` directory. 9 | 3. Run `python main.py` to visualize the execution. It will launch your browser to show the result. 10 | -------------------------------------------------------------------------------- /visualization/parsers/base.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | class BaseParser: 4 | def __init__(self, bft_dir): 5 | self.dir = bft_dir 6 | 7 | def load_logs(self): 8 | logs = dict() 9 | in_dir = self.dir + "/log" 10 | for filename in os.listdir(in_dir): 11 | node_id = int(filename[:filename.find(".log")]) 12 | with open(f"{in_dir}/{filename}", 'r') as infile: 13 | data = infile.read().splitlines() 14 | logs[node_id] = data 15 | return logs 16 | 17 | def parse(self): 18 | raise NotImplementedError() -------------------------------------------------------------------------------- /ba-algo/node.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const Logger = require('../lib/logger'); 3 | require('../lib/fp'); 4 | 5 | class Node { 6 | onMsgEvent(msgEvent) { 7 | this.clock = msgEvent.triggeredTime; 8 | } 9 | 10 | onTimeEvent(timeEvent) { 11 | this.clock = timeEvent.triggeredTime; 12 | } 13 | 14 | send(src, dst, msg) { 15 | if (this.isCooling) { 16 | return; 17 | } 18 | if (dst !== 'system') { 19 | this.logger.info(['send', this.clock, dst, JSON.stringify(msg)]); 20 | } 21 | const packet = { 22 | src: src, 23 | dst: dst, 24 | content: msg, 25 | sendTime: this.clock 26 | }; 27 | this.network.transfer(packet); 28 | } 29 | 30 | constructor(nodeID, nodeNum, network, registerTimeEvent) { 31 | this.nodeID = nodeID; 32 | this.nodeNum = nodeNum; 33 | this.logger = new Logger(this.nodeID); 34 | this.isCooling = false; 35 | this.network = network; 36 | this.registerTimeEvent = registerTimeEvent; 37 | this.clock = 0; 38 | } 39 | } 40 | module.exports = Node; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "consensus-bench", 3 | "version": "1.0.0", 4 | "description": "Benchmark framework for consensus protocol such as BA or blockchain", 5 | "main": "simulator.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start": "node --max-old-space-size=8192 simulator.js" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/CheshireCatNick/consensus-bench.git" 13 | }, 14 | "keywords": [ 15 | "blockchain", 16 | "consensus", 17 | "Byzantine", 18 | "agreement" 19 | ], 20 | "author": "Nicky", 21 | "license": "ISC", 22 | "bugs": { 23 | "url": "https://github.com/CheshireCatNick/consensus-bench/issues" 24 | }, 25 | "homepage": "https://github.com/CheshireCatNick/consensus-bench#readme", 26 | "dependencies": { 27 | "cli-color": "^1.3.0", 28 | "cli-progress": "^3.8.2", 29 | "clui": "^0.3.6", 30 | "colors": "^1.4.0", 31 | "fastpriorityqueue": "^0.6.1", 32 | "mathjs": "^10.0.0", 33 | "moment": "^2.22.2", 34 | "npm": "^6.14.15", 35 | "sleep": "^6.2.0", 36 | "uuid": "^3.3.2" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /lib/logger.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const config = require('../config'); 5 | 6 | class Logger { 7 | 8 | write(line) { 9 | fs.appendFileSync(`${Logger.dir}/${this.nodeID}.log`, line + '\n'); 10 | } 11 | 12 | logMsg(level, msgArr) { 13 | let msg = `[${level}] `; 14 | for (let i = 0; i < msgArr.length - 1; i++) 15 | msg += '[' + msgArr[i] + '] '; 16 | msg += msgArr[msgArr.length - 1]; 17 | if (config.logToFile) this.write(msg); 18 | } 19 | 20 | info(msgArr) { 21 | this.logMsg('info', msgArr); 22 | } 23 | 24 | warning(msgArr) { 25 | this.logMsg('warning', msgArr); 26 | } 27 | 28 | error(msgArr) { 29 | this.logMsg('error', msgArr); 30 | } 31 | 32 | round(n, digit) { 33 | digit = digit || 1; 34 | return Math.round(n / digit); 35 | } 36 | 37 | constructor(nodeID) { 38 | this.nodeID = nodeID; 39 | this.fileName = `${Logger.dir}/${this.nodeID}.log`; 40 | } 41 | 42 | static clearLogDir() { 43 | fs.rmSync(this.dir, { recursive: true, force: true }); 44 | fs.mkdirSync(this.dir); 45 | } 46 | } 47 | Logger.dir = './log'; 48 | module.exports = Logger; 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BFT Simulator 2 | A simulator for testing/verifying/benchmarking Byzantine Fault-Tolerant (BFT) protocols. 3 | 4 | P. -L. Wang, T. -W. Chao, C. -C. Wu and H. -C. Hsiao 5 | "Tool: An Efficient and Flexible Simulator for Byzantine Fault-Tolerant Protocols" 6 | 2022 52nd Annual IEEE/IFIP International Conference on Dependable Systems and Networks (DSN) 7 | 8 | --- 9 | 10 | ### Usage 11 | ``` 12 | npm i 13 | node main.js 14 | ``` 15 | 16 | ### Implemented Protocols 17 | - Async BA 18 | - PBFT 19 | - VMware BA 20 | - Algorand 21 | - HotStuff BFT (with a naive view synchronizer) 22 | - Libra BFT 23 | 24 | ### Attackers 25 | - Partitioner: partition network 26 | - VMware Static Attacker: static attacker for postponing VMware basic BA 27 | - VMware Adaptive Attacker: adaptive attacker for postponing VMware VRF BA 28 | 29 | ### Configurations 30 | Modify `config.js` to adjust the network environment, BFT protocol, number of nodes, attackers, etc. 31 | 32 | ### Reproduce Our Results 33 | The `examples` directory contains several scripts to run our experiments. 34 | 35 | ### Visualization 36 | We provide a python tool to visualize the execution of a BFT protocol. Please refer to the `README.md` file inside the `visualization` directory for more information. 37 | -------------------------------------------------------------------------------- /visualization/main.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | def get_config_protocol(dir): 4 | with open(f"{dir}/config.js", 'r') as infile: 5 | got = infile.read() 6 | begin = got.find("protocol:") + 9 7 | end = got.find(",", begin) 8 | return (got[begin:end].strip())[1:-1] 9 | 10 | if __name__ == '__main__': 11 | import argparse 12 | arg_parser = argparse.ArgumentParser(description='Visualize BFT simulation result.') 13 | arg_parser.add_argument("-p", "--protocol", help="specify the protocol (default: parse from config.js)", type=str) 14 | arg_parser.add_argument("-d", "--dir", help="path of BFT Simulator (default: current dir)", type=str, default=".") 15 | args = arg_parser.parse_args() 16 | 17 | protocol = args.protocol 18 | if protocol is None: 19 | protocol = get_config_protocol(args.dir) 20 | 21 | if protocol == "pbft": 22 | from parsers.pbft import PbftParser 23 | from visualizers.pbft import PbftVisualizer 24 | parser = PbftParser(args.dir) 25 | visualizer = PbftVisualizer() 26 | elif "hotstuff" in protocol: 27 | from parsers.hotstuff import HotStuffParser 28 | from visualizers.hotstuff import HotStuffVisualizer 29 | parser = HotStuffParser(args.dir) 30 | visualizer = HotStuffVisualizer() 31 | else: 32 | print(f"[!] Protocol {protocol} is currently not supported") 33 | exit() 34 | 35 | parsed = parser.parse() 36 | visualizer.draw(parsed) 37 | 38 | -------------------------------------------------------------------------------- /lib/fp.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // return [str(value), [element]] 4 | Array.prototype.groupBy = function(f) { 5 | const o = {}; 6 | Object(this).forEach(e => { 7 | const k = f(e); 8 | (k in o) ? o[k].push(e) : (o[k] = [e]); 9 | }); 10 | const a = []; 11 | for (let k in o) { 12 | a.push([k, o[k]]); 13 | } 14 | return a; 15 | }; 16 | // return an element in array 17 | Array.prototype.maxBy = function(f) { 18 | return Object(this).reduce((a, b) => f(a) > f(b) ? a : b); 19 | }; 20 | // return an element in array 21 | Array.prototype.minBy = function(f) { 22 | return Object(this).reduce((a, b) => f(a) < f(b) ? a : b); 23 | }; 24 | // return an element in array 25 | Array.prototype.max = function() { 26 | return Object(this).reduce((a, b) => (a > b) ? a : b); 27 | }; 28 | // return an element in array 29 | Array.prototype.min = function() { 30 | return Object(this).reduce((a, b) => (a < b) ? a : b); 31 | }; 32 | // return an array 33 | Array.prototype.flat = function() { 34 | return Object(this).reduce((o, e) => { 35 | return o.concat(e); 36 | }, []); 37 | }; 38 | // return true or false 39 | Array.prototype.has = function(e) { 40 | return Object(this).indexOf(e) !== -1; 41 | } 42 | // return an array with no duplicate according to f 43 | // O(n ^ 2), can be optimized to O(nlogn) 44 | Array.prototype.unique = function(f) { 45 | const r = []; 46 | Object(this).forEach(e => { 47 | if (r.some(re => 48 | f(re) !== undefined && f(e) !== undefined && f(re) === f(e))) { 49 | return; 50 | } 51 | r.push(e); 52 | }); 53 | return r; 54 | } 55 | //const a = [ {b: 1}, {b:1}, {b:2}, {c:3}, {c:4}, {c:3} ]; 56 | //console.log(a.unique(e => e.c)); 57 | -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const cliProgress = require('cli-progress'); 4 | const math = require('mathjs'); 5 | const Simulator = require("./simulator"); 6 | const config = require("./config"); 7 | 8 | const multibar = new cliProgress.MultiBar({ 9 | format: ' {bar} | {payload} | {value}/{total} | Percentage: {percentage} %| ETA: {eta}', 10 | hideCursor: true, 11 | barCompleteChar: '\u2588', 12 | barIncompleteChar: '\u2591', 13 | clearOnComplete: true, 14 | stopOnComplete: true 15 | }); 16 | 17 | // initialize simulator with config 18 | const s = new Simulator(config); 19 | 20 | // show progress bar during execution 21 | const progressBar = multibar.create(config.repeatTime, 0, { payload: `${config.protocol}-${config.nodeNum}-${config.byzantineNodeNum}-${config.networkDelay.mean}-${config.networkDelay.std}-${config.lambda}` }); 22 | s.onDecision = () => { 23 | progressBar.increment(); 24 | progressBar.render(); 25 | } 26 | 27 | // begin simulation 28 | s.startSimulation(); 29 | 30 | const pipeline = config.protocol.includes("hotstuff") || config.protocol === "libra"; 31 | 32 | // collect result 33 | const latencyData = s.simulationResults.map(x => pipeline ? x.latency / 100 : x.latency); 34 | const msgCountData = s.simulationResults.map(x => pipeline ? x.totalMsgCount / 100 : x.totalMsgCount); 35 | 36 | // show simulation result 37 | console.log(`\nProtocol: ${config.protocol}, (n, f) = (${config.nodeNum}, ${config.byzantineNodeNum}), attacker: ${config.attacker}`); 38 | console.log(`lambda (ms) = ${config.lambda * 1000}, network delay (ms): (mean, std) = (${config.networkDelay.mean * 1000}, ${config.networkDelay.std * 1000})`); 39 | console.log(`Time usage (ms): (mean, std) = (${math.mean(latencyData).toFixed(2)}, ${Math.round(math.std(latencyData))}), median = ${math.median(latencyData).toFixed(2)}`); 40 | console.log(`Message count: (mean, std) = (${math.mean(msgCountData).toFixed(2)}, ${math.std(msgCountData).toFixed(2)})`); 41 | -------------------------------------------------------------------------------- /attacker/partitioner.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const config = require('../config'); 4 | // create a partition between f and f + 1 non-Byzantine nodes 5 | class Partitioner { 6 | 7 | updateParam() { 8 | this.isPartitionResolved = false; 9 | this.registerTimeEvent( 10 | { name: 'resolvePartition' }, 11 | this.partitionResolveTime * 1000 12 | ); 13 | return false; 14 | } 15 | 16 | getDelay(mean, std) { 17 | let u = 0, v = 0; 18 | while (u === 0) u = Math.random(); 19 | while (v === 0) v = Math.random(); 20 | const _01BM = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v); 21 | const delay = _01BM * std + mean; 22 | return (delay < 0) ? 0 : delay; 23 | } 24 | 25 | getPartition(nodeID) { 26 | for (let i = 0; i < this.partitions.length; i++) { 27 | if (this.partitions[i].has(nodeID)) { 28 | return i; 29 | } 30 | } 31 | } 32 | 33 | attack(packets) { 34 | if (this.isPartitionResolved) return packets; 35 | packets.forEach((packet) => { 36 | const srcPartition = this.getPartition(packet.src); 37 | const dstPartition = this.getPartition(packet.dst); 38 | if (srcPartition !== dstPartition) { 39 | packet.delay = this.getDelay( 40 | this.partitionDelay.mean, 41 | this.partitionDelay.std 42 | ); 43 | } 44 | }); 45 | return packets; 46 | } 47 | 48 | onTimeEvent() { 49 | this.isPartitionResolved = true; 50 | } 51 | 52 | constructor(transfer, registerTimeEvent) { 53 | this.transfer = transfer; 54 | this.registerTimeEvent = registerTimeEvent; 55 | this.partitionResolveTime = 60; 56 | this.partitionDelay = { mean: 60, std: 1 }; 57 | this.isPartitionResolved = false; 58 | const partitionNum = 2; 59 | const correctNodeNum = config.nodeNum - config.byzantineNodeNum; 60 | const boundaries = []; 61 | for (let i = 1; i < partitionNum; i++) { 62 | boundaries.push(Math.floor(correctNodeNum / partitionNum) * i); 63 | } 64 | this.partitions = [[]]; 65 | let partitionIndex = 0; 66 | for (let nodeID = 1; nodeID <= correctNodeNum; nodeID++) { 67 | this.partitions[partitionIndex].push('' + nodeID); 68 | if (nodeID === boundaries[partitionIndex]) { 69 | partitionIndex++; 70 | this.partitions.push([]); 71 | } 72 | } 73 | this.registerTimeEvent( 74 | { name: 'resolvePartition' }, 75 | this.partitionResolveTime * 1000 76 | ); 77 | } 78 | } 79 | 80 | module.exports = Partitioner; 81 | -------------------------------------------------------------------------------- /examples/lambdas.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // this script run simulation through different lambda settings 3 | const cliProgress = require('cli-progress'); 4 | const math = require('mathjs'); 5 | const fs = require("fs"); 6 | const Simulator = require("../simulator"); 7 | const config = require("../config"); 8 | 9 | const info = `${config.protocol}-${config.nodeNum}-${config.byzantineNodeNum}-${config.networkDelay.mean}-${config.networkDelay.std}`; 10 | 11 | // configuration 12 | // set lambda from start ~ end (included), each time increased by delta 13 | const lambda_start = 0.1; 14 | const lambda_end = 2; 15 | const lambda_delta = 0.1; 16 | // log result 17 | const log = true; 18 | const clearLog = true; 19 | const logPath = "./experiments-log"; 20 | const filename = `${logPath}/${info}-lambda-${lambda_start}-${lambda_end}.csv`; 21 | 22 | const multibar = new cliProgress.MultiBar({ 23 | format: ' {bar} | {payload} | {value}/{total} | Percentage: {percentage} %| ETA: {eta}', 24 | hideCursor: true, 25 | barCompleteChar: '\u2588', 26 | barIncompleteChar: '\u2591', 27 | clearOnComplete: true, 28 | stopOnComplete: true 29 | }); 30 | 31 | // clear log 32 | if (clearLog && fs.existsSync(logPath)) 33 | fs.rmSync(logPath, { recursive: true, force: true }); 34 | 35 | if (log) { 36 | if (!fs.existsSync(logPath)) fs.mkdirSync(logPath); 37 | fs.writeFileSync(filename, "Lambda (ms),Time usage mean (ms),Time usage std (ms),Time usage median (ms),Message count mean,Message count std\n"); 38 | } 39 | 40 | for (let lambda = lambda_start; lambda <= lambda_end; lambda += lambda_delta) { 41 | lambda = parseFloat(lambda.toFixed(3)); 42 | config.lambda = lambda; 43 | const s = new Simulator(config); 44 | const progressBar = multibar.create(config.repeatTime, 0, { payload: `${info}-${config.lambda}` }); 45 | s.onDecision = () => { 46 | progressBar.increment(); 47 | progressBar.render(); 48 | } 49 | s.startSimulation(); 50 | const latencyData = s.simulationResults.map(x => { return x.latency }); 51 | const msgCountData = s.simulationResults.map(x => { return x.totalMsgCount }); 52 | 53 | if (log) { 54 | fs.appendFileSync(filename, `${1000 * lambda},${Math.round(math.mean(latencyData))},${Math.round(math.std(latencyData))},${Math.round(math.median(latencyData))},`); 55 | fs.appendFileSync(filename, `${math.mean(msgCountData)},${math.std(msgCountData).toFixed(2)}\n`); 56 | console.log(""); 57 | } 58 | else { 59 | console.log(`\nTime usage (ms): (mean, std) = (${Math.round(math.mean(latencyData))}, ${Math.round(math.std(latencyData))}), median = ${Math.round(math.median(latencyData))}`); 60 | console.log(`Message count: (mean, std) = (${Math.round(math.mean(msgCountData))}, ${math.std(msgCountData).toFixed(2)})`); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /attacker/vmware-attacker/static-attacker.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // implement static attack for VMware BA 3 | const config = require('../../config'); 4 | const Attacker = require('../attacker'); 5 | 6 | class StaticAttacker extends Attacker { 7 | 8 | attack(packets) { 9 | // filter packets of controlled Byzantine nodes 10 | const returnPackets = packets.filter(packet => { 11 | return !this.byzantines.has(packet.src); 12 | }); 13 | if (this.mode === 'basic' || returnPackets.length === 0) { 14 | return returnPackets; 15 | } 16 | else if (this.mode === 'vrf' && 17 | returnPackets[0].content.type === 'fl-propose') { 18 | const msg = returnPackets[0].content; 19 | this.propose.push(msg); 20 | if (this.propose.length === 21 | config.nodeNum - this.maxByzantineNodeNum) { 22 | //console.log('find best vrf except byzantines'); 23 | this.propose.sort((msgA, msgB) => { 24 | if (msgA.kL < msgB.kL) { 25 | return 1; 26 | } 27 | else if (msgA.kL > msgB.kL) { 28 | return -1; 29 | } 30 | else { 31 | return (msgA.proposeMsg.y < msgB.proposeMsg.y) ? 1 : -1; 32 | } 33 | }); 34 | const bestProposal = this.propose[0]; 35 | // try if we can dice a better value 36 | for (let chance = 0; chance < this.maxByzantineNodeNum; chance++) { 37 | const y = Math.floor(Math.random() * 10000 + 1); 38 | if (y > bestProposal.proposeMsg.y) { 39 | // send fork value to some honest nodes 40 | const proposeMsg = { 41 | sender: '2', 42 | type: 'fl-propose', 43 | proposeMsg: { 44 | sender: '2', 45 | k: bestProposal.proposeMsg.k, 46 | type: 'propose', 47 | vL: 'x'.repeat(32), 48 | // VRF 49 | y: y 50 | }, 51 | kL: bestProposal.kL, 52 | CL: bestProposal.CL 53 | }; 54 | for (let nodeID = this.maxByzantineNodeNum + 2; 55 | nodeID <= config.nodeNum; nodeID++) { 56 | returnPackets.push({ 57 | src: '2', 58 | dst: '' + nodeID, 59 | content: proposeMsg, 60 | delay: 0 61 | }); 62 | } 63 | break; 64 | } 65 | } 66 | this.propose = []; 67 | } 68 | } 69 | return returnPackets; 70 | } 71 | 72 | constructor(transfer, registerTimeEvent) { 73 | super(transfer, registerTimeEvent); 74 | this.byzantines = []; 75 | this.maxByzantineNodeNum = (config.nodeNum % 2 === 0) ? 76 | config.nodeNum / 2 - 1 : Math.floor(config.nodeNum / 2); 77 | for (let nodeID = 2; nodeID <= this.maxByzantineNodeNum + 1; nodeID++) { 78 | this.byzantines.push('' + nodeID); 79 | } 80 | console.log(this.byzantines); 81 | this.mode = 'vrf'; 82 | this.propose = []; 83 | } 84 | } 85 | 86 | module.exports = StaticAttacker; 87 | -------------------------------------------------------------------------------- /examples/views.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // This script records nodes' view during protocol execution 3 | const cliProgress = require('cli-progress'); 4 | const math = require('mathjs'); 5 | const fs = require('fs'); 6 | const Simulator = require("../simulator"); 7 | const config = require("../config"); 8 | 9 | // configuration 10 | const viewPath = "./views"; // the dir to put logs in it 11 | const clearLog = true; // change to false if old logs should be preserved 12 | 13 | // initialize simulator with config 14 | const s = new Simulator(config); 15 | const info = `${config.protocol}-${config.nodeNum}-${config.byzantineNodeNum}-${config.networkDelay.mean}-${config.networkDelay.std}-${config.lambda}`; 16 | 17 | // show progress bar during execution 18 | const multibar = new cliProgress.MultiBar({ 19 | format: ' {bar} | {payload} | {value}/{total} | Percentage: {percentage} %| ETA: {eta}', 20 | hideCursor: true, 21 | barCompleteChar: '\u2588', 22 | barIncompleteChar: '\u2591', 23 | clearOnComplete: true, 24 | stopOnComplete: true 25 | }); 26 | const progressBar = multibar.create(config.repeatTime, 0, { payload: info }); 27 | 28 | // record views 29 | let maxViewDiff = 0; 30 | let recordedViews = { timestamp: [] }; 31 | 32 | const getViewDifference = () => { 33 | let minView = undefined; 34 | let maxView = undefined; 35 | for (let nodeID = 1; nodeID <= s.correctNodeNum; nodeID++) { 36 | const currView = s.nodes[nodeID].lastVotedView || 0; 37 | if (minView === undefined || minView > currView) { 38 | minView = currView; 39 | } 40 | if (maxView === undefined || maxView < currView) { 41 | maxView = currView; 42 | } 43 | } 44 | if (maxView !== undefined && minView !== undefined && maxView - minView > maxViewDiff) { 45 | maxViewDiff = maxView - minView; 46 | } 47 | } 48 | 49 | const recordNodesView = () => { 50 | // Record current timestamp 51 | recordedViews['timestamp'].push(s.clock.toFixed(2)); 52 | 53 | // Record views 54 | for (let nodeID = 1; nodeID <= s.correctNodeNum; nodeID++) { 55 | // Init new array for each node 56 | if (!recordedViews[nodeID]) recordedViews[nodeID] = []; 57 | 58 | let nodeView = s.nodes[nodeID].lastVotedView || 0; 59 | recordedViews[nodeID].push(nodeView); 60 | } 61 | } 62 | 63 | const writeViewsToFile = (filename) => { 64 | fs.writeFileSync(filename, `${maxViewDiff}\n`); 65 | fs.appendFileSync(filename, recordedViews['timestamp'].join(",") + "\n"); 66 | for (let nodeID = 1; nodeID <= s.correctNodeNum; nodeID++) { 67 | fs.appendFileSync(filename, recordedViews[nodeID].join(",") + "\n"); 68 | } 69 | } 70 | 71 | // define callback functions 72 | s.onDecision = () => { 73 | progressBar.increment(); 74 | progressBar.render(); 75 | writeViewsToFile(`${viewPath}/${info}_${s.simCount + 1}.csv`); 76 | maxViewDiff = 0; 77 | recordedViews = { timestamp: [] }; 78 | } 79 | 80 | s.onEventsProccessed = () => { 81 | getViewDifference(); 82 | recordNodesView(); 83 | } 84 | 85 | // clear log 86 | if (clearLog && fs.existsSync(viewPath)) 87 | fs.rmSync(viewPath, { recursive: true, force: true }); 88 | if (!fs.existsSync(viewPath)) fs.mkdirSync(viewPath); 89 | 90 | // begin simulation 91 | s.startSimulation(); 92 | 93 | // collect result 94 | const latencyData = s.simulationResults.map(x => { return x.latency }); 95 | const msgCountData = s.simulationResults.map(x => { return x.totalMsgCount }); 96 | 97 | // show simulation result 98 | console.log(`\nProtocol: ${config.protocol}, (n, f) = (${config.nodeNum + config.byzantineNodeNum}, ${config.byzantineNodeNum}), attacker: ${config.attacker}`); 99 | console.log(`lambda (ms) = ${config.lambda * 1000}, network delay (ms): (mean, std) = (${config.networkDelay.mean * 1000}, ${config.networkDelay.std * 1000})`); 100 | console.log(`Time usage (ms): (mean, std) = (${Math.round(math.mean(latencyData))}, ${Math.round(math.std(latencyData))}), median = ${Math.round(math.median(latencyData))}`); 101 | console.log(`Message count: (mean, std) = (${Math.round(math.mean(msgCountData))}, ${math.std(msgCountData).toFixed(2)})`); 102 | -------------------------------------------------------------------------------- /validator/audit_queue.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // implement network that pass JSON object 3 | const config = require('../config'); 4 | const fs = require('fs'); 5 | 6 | class MockNetwork { 7 | 8 | transfer(packet) { 9 | if (packet.dst === 'system') { 10 | this.sendToSystem(packet.content); 11 | return; 12 | } 13 | if (this.init) { 14 | this.startTime = Date.now(); 15 | this.init = false; 16 | } 17 | /* 18 | if (packet.dst !== 'broadcast' && 19 | this.availableDst.has(packet.dst) && 20 | this.sockets[packet.dst] === undefined) { 21 | this.queue.push(packet); 22 | return; 23 | }*/ 24 | let packets = []; 25 | // add delay according to config 26 | if (packet.dst === 'broadcast') { 27 | for (let nodeID of this.availableDst) { 28 | if (nodeID === packet.src) { 29 | continue; 30 | } 31 | packet.delay = 0; 32 | packet.dst = nodeID; 33 | packets.push(JSON.parse(JSON.stringify(packet))); 34 | } 35 | } 36 | else { 37 | packet.delay = 0; 38 | packets.push(packet); 39 | } 40 | this.totalMsgCount += packets.length; 41 | 42 | packets.forEach((packet) => { 43 | if (this.msgCount[packet.content.type] === undefined) { 44 | this.msgCount[packet.content.type] = 1; 45 | } 46 | else { 47 | this.msgCount[packet.content.type]++; 48 | } 49 | this.registerMsgEvent(packet); 50 | }); 51 | } 52 | 53 | 54 | removeNodes() { 55 | this.totalMsgCount = 0; 56 | this.totalMsgBytes = 0; 57 | this.msgCount = {}; 58 | this.availableDst = []; 59 | this.init = true; 60 | } 61 | addNodes(nodes) { 62 | for (let nodeID in nodes) { 63 | this.availableDst.push(nodeID); 64 | } 65 | } 66 | 67 | constructor(sendToSystem, registerMsgEvent) { 68 | this.sendToSystem = sendToSystem; 69 | this.registerMsgEvent = registerMsgEvent; 70 | 71 | this.msgCount = {}; 72 | this.totalMsgCount = 0; 73 | this.totalMsgBytes = 0; 74 | this.init = true; 75 | this.availableDst = []; 76 | }} 77 | 78 | class AuditChecker { 79 | 80 | addMsg(msg) { 81 | this.queue.addMsg(msg); 82 | } 83 | 84 | logMsg(msgEvent) { 85 | this.queue.push(msgEvent); 86 | } 87 | 88 | logToFile() { 89 | fs.appendFileSync(`./${this.logPath}.log`, JSON.stringify(this.queue)); 90 | } 91 | 92 | addMsgEvent(msgEvent) { 93 | 94 | } 95 | 96 | logFromFile() { 97 | let queue = JSON.parse(fs.readFileSync(`./${this.logPath}.log`)); 98 | this.queue = queue.reverse(); 99 | } 100 | 101 | isMatch(groundTruth, event) { 102 | if (groundTruth['type'] !== event['type']) { 103 | return false; 104 | } 105 | 106 | if ( 107 | groundTruth['packet']['src'] !== event['packet']['src'] || 108 | groundTruth['packet']['dst'] !== event['packet']['dst'] || 109 | groundTruth['packet']['content']['type'] !== event['packet']['content']['type'] 110 | // groundTruth['packet']['content']['v'] !== event['packet']['content']['v'] 111 | ) { 112 | return false; 113 | } 114 | return true; 115 | } 116 | 117 | nextMsgEvent() { 118 | let peek = this.queue[this.queue.length - 1]; 119 | for (let i = 0; i < this.eventBasket.length; i++) { 120 | let event = this.eventBasket[i]; 121 | if (this.isMatch(peek, event)) { 122 | this.eventBasket.splice(i, 1); 123 | this.queue.pop(); 124 | return event; 125 | } 126 | } 127 | return null; 128 | } 129 | 130 | constructor(logPath, sendToSystem) { 131 | this.logPath = logPath; 132 | this.queue = []; 133 | this.eventBasket = []; 134 | this.clock = 0; 135 | 136 | this.network = new MockNetwork(sendToSystem, (packet) => { 137 | this.eventBasket.push({ 138 | type: 'msg-event', 139 | packet: packet, 140 | dst: packet.dst, 141 | registeredTime: this.clock, 142 | triggeredTime: this.clock, 143 | }); 144 | }) 145 | } 146 | } 147 | 148 | module.exports = AuditChecker; -------------------------------------------------------------------------------- /visualization/visualizers/pbft.py: -------------------------------------------------------------------------------- 1 | from .base import BaseVisualizer 2 | from collections import defaultdict 3 | import plotly.graph_objects as go 4 | 5 | class PbftVisualizer(BaseVisualizer): 6 | def draw(self, parsed_data): 7 | self.raw = parsed_data 8 | self.fig = go.Figure() 9 | 10 | self.process_data() 11 | 12 | self.draw_views() 13 | self.draw_packets() 14 | self.draw_events() 15 | 16 | self.fig.update_yaxes(dtick=1, fixedrange=True) 17 | self.fig.update_layout(hovermode="x unified") 18 | self.fig.show() 19 | 20 | def process_data(self): 21 | self.num_of_nodes = self.raw['info']['nodes'] 22 | self.process_packets() 23 | self.process_events() 24 | 25 | def process_packets(self): 26 | self.packets = [] 27 | type_to_pkts = defaultdict(list) 28 | for pkt in self.raw['pkts']: 29 | type_to_pkts[pkt['type']].append(pkt) 30 | 31 | for _type, _pkts in type_to_pkts.items(): 32 | timestamps = [] 33 | nodes = [] 34 | 35 | for _pkt in _pkts: 36 | timestamps += [_pkt["send_time"], _pkt["recv_time"], None] 37 | nodes += [_pkt["src"], _pkt["dst"], None] 38 | 39 | self.packets.append({ 40 | "timestamps": timestamps, 41 | "nodes": nodes, 42 | "type": _type 43 | }) 44 | 45 | def process_events(self): 46 | self.events = self.raw['events'] 47 | self.type_to_events = defaultdict(list) 48 | for event in self.events: 49 | self.type_to_events[event['type']].append(event) 50 | self.process_views() 51 | 52 | def process_views(self): 53 | node_to_last_time = [0 for _ in range(self.num_of_nodes)] 54 | node_to_last_leader = [0 for _ in range(self.num_of_nodes)] 55 | self.leader_to_timestamps = [[] for _ in range(self.num_of_nodes)] 56 | self.leader_to_nodes = [[] for _ in range(self.num_of_nodes)] 57 | for view_event in self.type_to_events['new-view']: 58 | node_id = view_event["node"] 59 | _leader = node_to_last_leader[node_id - 1] 60 | 61 | self.leader_to_timestamps[_leader] += [node_to_last_time[node_id - 1], view_event["timestamp"], None] 62 | self.leader_to_nodes[_leader] += [node_id, node_id, None] 63 | 64 | node_to_last_leader[node_id - 1] = view_event['new-view'] % self.num_of_nodes 65 | node_to_last_time[node_id - 1] = view_event["timestamp"] 66 | 67 | # process last view 68 | for node_id in range(self.num_of_nodes): 69 | _leader = node_to_last_leader[node_id] 70 | begin_time = node_to_last_time[node_id] 71 | # get the timestamp of the last event 72 | last_time = begin_time 73 | for e in self.events: 74 | if e["node"] - 1 == node_id and e["timestamp"] > last_time: 75 | last_time = e["timestamp"] 76 | self.leader_to_timestamps[_leader] += [begin_time, last_time, None] 77 | self.leader_to_nodes[_leader] += [node_id + 1, node_id + 1, None] 78 | 79 | del self.type_to_events['new-view'] 80 | 81 | def draw_packets(self): 82 | for pkt in self.packets: 83 | self.fig.add_trace(go.Scatter( 84 | x = pkt["timestamps"], y = pkt["nodes"], name = pkt["type"], line = {'color': "#555"} 85 | )) 86 | 87 | def draw_events(self): 88 | symbols_dict = defaultdict(lambda : ["circle", "black"]) 89 | symbols_dict['new-view'] = ["x", 'red'] 90 | symbols_dict['reset-timeout'] = ['diamond', "yellow"] 91 | symbols_dict['enough-vote'] = ['star-open', "red"] 92 | 93 | for _type, _events in self.type_to_events.items(): 94 | timestamps = [] 95 | nodes = [] 96 | 97 | for _event in _events: 98 | timestamps.append(_event['timestamp']) 99 | nodes.append(_event['node']) 100 | 101 | self.fig.add_trace(go.Scatter( 102 | x = timestamps, y = nodes, name = _type, mode = 'markers', marker_symbol = symbols_dict[_type][0], marker = {"size": 15, "color": symbols_dict[_type][1]} 103 | )) 104 | 105 | def draw_views(self): 106 | for i in range(self.num_of_nodes): 107 | self.fig.add_trace(go.Scatter( 108 | x = self.leader_to_timestamps[i], 109 | y = self.leader_to_nodes[i], 110 | name = f"Leader {i + 1}", 111 | hovertext = f"Leader {i + 1}", 112 | line = { 'width': 20 }, 113 | opacity = 0.5 114 | )) 115 | 116 | -------------------------------------------------------------------------------- /visualization/visualizers/hotstuff.py: -------------------------------------------------------------------------------- 1 | from .base import BaseVisualizer 2 | from collections import defaultdict 3 | import plotly.graph_objects as go 4 | 5 | class HotStuffVisualizer(BaseVisualizer): 6 | def draw(self, parsed_data): 7 | self.raw = parsed_data 8 | self.fig = go.Figure() 9 | 10 | self.process_data() 11 | 12 | self.draw_views() 13 | self.draw_packets() 14 | self.draw_events() 15 | 16 | self.fig.update_yaxes(dtick=1, fixedrange=True) 17 | self.fig.update_xaxes(rangemode="nonnegative", autorange=False, range=[0, 100000]) 18 | self.fig.update_layout(hovermode="x unified") 19 | self.fig.show() 20 | 21 | def process_data(self): 22 | self.num_of_nodes = self.raw['info']['nodes'] 23 | self.process_packets() 24 | self.process_events() 25 | 26 | def process_packets(self): 27 | self.packets = [] 28 | type_to_pkts = defaultdict(list) 29 | for pkt in self.raw['pkts']: 30 | type_to_pkts[pkt['type']].append(pkt) 31 | 32 | for _type, _pkts in type_to_pkts.items(): 33 | timestamps = [] 34 | nodes = [] 35 | 36 | for _pkt in _pkts: 37 | timestamps += [_pkt["send_time"], _pkt["recv_time"], None] 38 | nodes += [_pkt["src"], _pkt["dst"], None] 39 | 40 | self.packets.append({ 41 | "timestamps": timestamps, 42 | "nodes": nodes, 43 | "type": _type 44 | }) 45 | 46 | def process_events(self): 47 | self.events = self.raw['events'] 48 | self.type_to_events = defaultdict(list) 49 | for event in self.events: 50 | self.type_to_events[event['type']].append(event) 51 | self.process_views() 52 | 53 | def process_views(self): 54 | node_to_last_time = [0 for _ in range(self.num_of_nodes)] 55 | node_to_last_leader = [0 for _ in range(self.num_of_nodes)] 56 | self.leader_to_timestamps = [[] for _ in range(self.num_of_nodes)] 57 | self.leader_to_nodes = [[] for _ in range(self.num_of_nodes)] 58 | for view_event in self.type_to_events['new-view']: 59 | node_id = view_event["node"] 60 | _leader = node_to_last_leader[node_id - 1] 61 | 62 | self.leader_to_timestamps[_leader] += [node_to_last_time[node_id - 1], view_event["timestamp"], None] 63 | self.leader_to_nodes[_leader] += [node_id, node_id, None] 64 | 65 | node_to_last_leader[node_id - 1] = view_event['new-view'] % self.num_of_nodes 66 | node_to_last_time[node_id - 1] = view_event["timestamp"] 67 | 68 | # process last view 69 | for node_id in range(self.num_of_nodes): 70 | _leader = node_to_last_leader[node_id] 71 | begin_time = node_to_last_time[node_id] 72 | # get the timestamp of the last event 73 | last_time = begin_time 74 | for e in self.events: 75 | if e["node"] - 1 == node_id and e["timestamp"] > last_time: 76 | last_time = e["timestamp"] 77 | self.leader_to_timestamps[_leader] += [begin_time, last_time, None] 78 | self.leader_to_nodes[_leader] += [node_id + 1, node_id + 1, None] 79 | 80 | del self.type_to_events['new-view'] 81 | 82 | def draw_packets(self): 83 | for pkt in self.packets: 84 | self.fig.add_trace(go.Scatter( 85 | x = pkt["timestamps"], y = pkt["nodes"], name = pkt["type"], line = {'color': "#555"} 86 | )) 87 | 88 | def draw_events(self): 89 | symbols_dict = defaultdict(lambda : ["circle", "black"]) 90 | symbols_dict['new-view'] = ["x", 'red'] 91 | symbols_dict['reset-timeout'] = ['diamond', "yellow"] 92 | symbols_dict['enough-vote'] = ['star-open', "red"] 93 | 94 | for _type, _events in self.type_to_events.items(): 95 | timestamps = [] 96 | nodes = [] 97 | 98 | for _event in _events: 99 | timestamps.append(_event['timestamp']) 100 | nodes.append(_event['node']) 101 | 102 | self.fig.add_trace(go.Scatter( 103 | x = timestamps, y = nodes, name = _type, mode = 'markers', marker_symbol = symbols_dict[_type][0], marker = {"size": 15, "color": symbols_dict[_type][1]} 104 | )) 105 | 106 | def draw_views(self): 107 | for i in range(self.num_of_nodes): 108 | self.fig.add_trace(go.Scatter( 109 | x = self.leader_to_timestamps[i], 110 | y = self.leader_to_nodes[i], 111 | name = f"Leader {i + 1}", 112 | hovertext = f"Leader {i + 1}", 113 | line = { 'width': 20 }, 114 | opacity = 0.5 115 | )) 116 | 117 | -------------------------------------------------------------------------------- /attacker/vmware-attacker/adaptive-attacker.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // implement adaptive attack for VMware BA 3 | const config = require('../../config'); 4 | const Attacker = require('../attacker'); 5 | 6 | class AdaptiveAttacker extends Attacker { 7 | 8 | updateParam() { 9 | this.byzantines = []; 10 | return false; 11 | } 12 | 13 | attack(packets) { 14 | const msg = packets[0].content; 15 | if (this.mode === 'vrf' && 16 | msg.type === 'fl-propose') { 17 | this.propose.push(msg); 18 | if (this.propose.length == config.nodeNum) { 19 | //console.log('find best vrf except byzantines'); 20 | this.propose.sort((msgA, msgB) => { 21 | if (msgA.kL < msgB.kL) { 22 | return 1; 23 | } 24 | else if (msgA.kL > msgB.kL) { 25 | return -1; 26 | } 27 | else { 28 | return (msgA.proposeMsg.y < msgB.proposeMsg.y) ? 1 : -1; 29 | } 30 | }); 31 | const bestProposal = this.propose[0]; 32 | //console.log(bestProposal); 33 | // adapt leader 34 | if (this.byzantines.has(bestProposal.sender)) { 35 | //console.log('lucky VRF'); 36 | } 37 | else if (this.byzantines.length < this.f) { 38 | //console.log('adapting: ', bestProposal.sender); 39 | this.byzantines.push(bestProposal.sender); 40 | } 41 | // send fork value 42 | if (this.byzantines.has(bestProposal.sender)) { 43 | const forkProposeMsg = JSON.parse(JSON.stringify(bestProposal)); 44 | forkProposeMsg.proposeMsg.vL = 'x'.repeat(32); 45 | // broadcast to half of the honest nodes 46 | for (let nodeID = 1; nodeID <= (config.nodeNum / 2); nodeID++) { 47 | packets.push({ 48 | src: bestProposal.sender, 49 | dst: '' + nodeID, 50 | content: forkProposeMsg, 51 | delay: 0 52 | }); 53 | } 54 | } 55 | this.propose = []; 56 | } 57 | } 58 | else if (this.mode === 'adaptive') { 59 | if (msg.type === 'fl-propose') { 60 | this.flPropose.push(msg); 61 | } 62 | else if (msg.type === 'elect') { 63 | this.elect.push(msg); 64 | if (this.elect.length == config.nodeNum) { 65 | //console.log('find best vrf except byzantines'); 66 | this.elect.sort((msgA, msgB) => { 67 | return (msgA.y < msgB.y) ? 1 : -1; 68 | }); 69 | const bestProposal = this.elect[0]; 70 | 71 | //console.log(bestProposal); 72 | // adapt leader 73 | if (this.byzantines.has(bestProposal.sender)) { 74 | //console.log('lucky VRF'); 75 | } 76 | else if (this.byzantines.length < this.f) { 77 | //console.log('adapting: ', bestProposal.sender); 78 | this.byzantines.push(bestProposal.sender); 79 | } 80 | // useless to send fork value here 81 | if (this.byzantines.has(bestProposal.sender)) { 82 | const flProposeMsg = this.flPropose.find( 83 | (msg) => msg.sender === bestProposal.sender 84 | ); 85 | const forkProposeMsg = JSON.parse(JSON.stringify(flProposeMsg)); 86 | forkProposeMsg.proposeMsg.vL = 'x'.repeat(32); 87 | forkProposeMsg.proposeMsg.prepared = []; 88 | // broadcast to half of the honest nodes 89 | for (let nodeID = 1; nodeID <= (config.nodeNum / 2); nodeID++) { 90 | packets.push({ 91 | src: bestProposal.sender, 92 | dst: '' + nodeID, 93 | content: forkProposeMsg, 94 | delay: 0 95 | }); 96 | } 97 | } 98 | this.elect = []; 99 | this.flPropose = []; 100 | } 101 | } 102 | } 103 | return packets; 104 | } 105 | 106 | constructor(transfer, registerTimeEvent) { 107 | super(transfer, registerTimeEvent); 108 | this.f = (config.nodeNum % 2 === 0) ? 109 | config.nodeNum / 2 - 1 : Math.floor(config.nodeNum / 2); 110 | this.propose = []; 111 | this.elect = []; 112 | this.flPropose = []; 113 | this.byzantines = []; 114 | this.mode = 'adaptive'; 115 | } 116 | } 117 | 118 | module.exports = AdaptiveAttacker; 119 | -------------------------------------------------------------------------------- /network/network.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // implement network that pass JSON object 3 | let config = require('../config'); 4 | const Attacker = (config.attacker) ? 5 | require('../attacker/' + config.attacker) : undefined; 6 | 7 | class Network { 8 | 9 | getDelay(mean, std) { 10 | function get01BM() { 11 | let u = 0, v = 0; 12 | while (u === 0) u = Math.random(); 13 | while (v === 0) v = Math.random(); 14 | return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v); 15 | } 16 | const delay = get01BM() * std + mean; 17 | return (delay < 0) ? 0 : delay; 18 | } 19 | 20 | getJSONSize(json) { 21 | let size = 0; 22 | for (let key in json) { 23 | size += key.length; 24 | switch (typeof json[key]) { 25 | case 'string': 26 | // a terrible workaround to avoid size difference 27 | // i is sender in PBFT 28 | if (key === 'sender' || key === 'i' || key === 'y') { 29 | size += 4; 30 | } 31 | else { 32 | size += json[key].length; 33 | } 34 | break; 35 | case 'number': 36 | size += 4; 37 | break; 38 | case 'object': 39 | if (Array.isArray(json[key])) { 40 | // array of obj 41 | for (let obj of json[key]) { 42 | size += this.getJSONSize(obj); 43 | } 44 | } 45 | else { 46 | // normal json 47 | size += this.getJSONSize(json[key]); 48 | } 49 | break; 50 | 51 | default: 52 | break; 53 | } 54 | } 55 | return size; 56 | } 57 | 58 | transfer(packet) { 59 | if (packet.dst === 'system') { 60 | this.sendToSystem(packet.content); 61 | return; 62 | } 63 | if (this.init) { 64 | this.startTime = Date.now(); 65 | this.init = false; 66 | } 67 | let packets = []; 68 | // add delay according to config 69 | if (packet.dst === 'broadcast') { 70 | for (let nodeID of this.availableDst) { 71 | if (nodeID === packet.src) { 72 | continue; 73 | } 74 | packet.delay = 75 | this.getDelay(config.networkDelay.mean, config.networkDelay.std); 76 | packet.dst = nodeID; 77 | packets.push(JSON.parse(JSON.stringify(packet))); 78 | } 79 | } 80 | else { 81 | packet.delay = 82 | this.getDelay(config.networkDelay.mean, config.networkDelay.std); 83 | packets.push(packet); 84 | } 85 | // attacker attack function 86 | if (Attacker !== undefined && 87 | packet.src !== 'system' && packet.dst !== 'system' && 88 | packet.src !== 'attacker' && packet.dst !== 'attacker') { 89 | packets = this.attacker.attack(packets); 90 | // filter unavailable dst packets 91 | packets = packets 92 | .filter(packet => this.availableDst.has(packet.dst)); 93 | } 94 | this.totalMsgCount += packets.length; 95 | this.totalMsgBytes += packets.reduce( 96 | (sum, packet) => sum + this.getJSONSize(packet.content), 0); 97 | // send packets 98 | packets.forEach((packet) => { 99 | if (this.msgCount[packet.content.type] === undefined) { 100 | this.msgCount[packet.content.type] = 1; 101 | } 102 | else { 103 | this.msgCount[packet.content.type]++; 104 | } 105 | this.registerMsgEvent(packet, packet.delay * 1000); 106 | }); 107 | } 108 | 109 | removeNodes() { 110 | this.totalMsgCount = 0; 111 | this.totalMsgBytes = 0; 112 | this.msgCount = {}; 113 | this.availableDst = []; 114 | this.init = true; 115 | } 116 | 117 | addNodes(nodes) { 118 | for (let nodeID in nodes) { 119 | this.availableDst.push(nodeID); 120 | } 121 | } 122 | 123 | constructor(sendToSystem, registerMsgEvent, registerAttackerTimeEvent, eventQ, nodeNum, byzantinNodeNum, getClockTime, customized_config) { 124 | if (customized_config !== undefined) { 125 | config = customized_config; 126 | } 127 | this.sendToSystem = sendToSystem; 128 | this.registerMsgEvent = registerMsgEvent; 129 | if (Attacker !== undefined) { 130 | this.attacker = new Attacker( 131 | (packet) => this.transfer(packet), 132 | registerAttackerTimeEvent, 133 | eventQ, 134 | nodeNum, 135 | byzantinNodeNum, 136 | getClockTime, 137 | ); 138 | } 139 | this.msgCount = {}; 140 | this.totalMsgCount = 0; 141 | this.totalMsgBytes = 0; 142 | this.init = true; 143 | this.availableDst = []; 144 | this.nodeNum; 145 | this.byzantinNodeNum; 146 | } 147 | } 148 | 149 | module.exports = Network; 150 | -------------------------------------------------------------------------------- /visualization/parsers/pbft.py: -------------------------------------------------------------------------------- 1 | from .base import BaseParser 2 | import json 3 | 4 | class PbftParser(BaseParser): 5 | def __init__(self, bft_dir): 6 | super().__init__(bft_dir) 7 | 8 | def parse(self): 9 | self.logs = self.load_logs() 10 | 11 | pkts = self.parse_packets() 12 | events = self.parse_events() 13 | 14 | return { 15 | "info": {"nodes": len(self.logs)}, 16 | "pkts": pkts, 17 | "events": events 18 | } 19 | 20 | def parse_send(self, line): 21 | tokens = line.split() 22 | timestamp = round(float(tokens[2][1:-1])) 23 | dst = tokens[3][1:-1] 24 | raw_data = line[line.find("{"):] 25 | data = json.loads(raw_data) 26 | 27 | return { 28 | "send_time": timestamp, 29 | "recv_time": -1, 30 | "src": int(data["i"]), 31 | "dst": int(dst) if dst != "broadcast" else dst, 32 | "req": data['d'], 33 | "type": data['type'], 34 | "data": raw_data 35 | } 36 | 37 | def parse_recv(self, line): 38 | tokens = line.split() 39 | timestamp = round(float(tokens[2][1:-1])) 40 | raw_data = line[line.find("{"):] 41 | data = json.loads(raw_data) 42 | 43 | return { 44 | "recv_time": timestamp, 45 | "src": int(data["i"]), 46 | "req": data["d"], 47 | "type": data["type"] 48 | } 49 | 50 | def parse_packets(self): 51 | pkts = [] 52 | src_dst_req_type_to_pkt = dict() 53 | src_dst_req_type_to_recv = dict() 54 | for node_id in self.logs: 55 | for line in self.logs[node_id]: 56 | is_send = "send" in line 57 | is_recv = "recv" in line 58 | if not is_send and not is_recv: 59 | continue 60 | 61 | if is_send: 62 | pkt = self.parse_send(line) 63 | if pkt['dst'] == 'broadcast': 64 | for i in range(1, len(self.logs) + 1): 65 | if i == node_id: 66 | continue 67 | new_pkt = pkt.copy() 68 | new_pkt['dst'] = i 69 | _key = f"{node_id}_{i}_{pkt['req']}_{pkt['type']}" 70 | if _key in src_dst_req_type_to_pkt: 71 | print(f"[Warning] duplicate packet: {_key}") 72 | src_dst_req_type_to_pkt[_key] = new_pkt 73 | else: 74 | _key = f"{node_id}_{pkt['dst']}_{pkt['req']}_{pkt['type']}" 75 | if _key in src_dst_req_type_to_pkt: 76 | print(f"[Warning] duplicate packet: {_key}") 77 | src_dst_req_type_to_pkt[_key] = pkt 78 | else: 79 | recv = self.parse_recv(line) 80 | _key = f"{recv['src']}_{node_id}_{recv['req']}_{recv['type']}" 81 | if _key in src_dst_req_type_to_recv: 82 | print(f"[Warning] {_key} has already been received") 83 | src_dst_req_type_to_recv[_key] = recv 84 | 85 | for _key, pkt in src_dst_req_type_to_pkt.items(): 86 | if _key not in src_dst_req_type_to_recv: 87 | print(f"[Warning] Missing recv pkt for {_key}") 88 | continue 89 | pkt['recv_time'] = src_dst_req_type_to_recv[_key]['recv_time'] 90 | pkts.append(pkt) 91 | del src_dst_req_type_to_recv[_key] 92 | 93 | if len(src_dst_req_type_to_recv) != 0: 94 | print(f"[Warning] {len(src_dst_req_type_to_recv)} receives don't have corresponding sending packets") 95 | 96 | return pkts 97 | 98 | def parse_new_view(self, line, node_id): 99 | tokens = line.split() 100 | timestamp = round(float(tokens[1][1:-1])) 101 | 102 | return { 103 | "node": node_id, 104 | "type": "new-view", 105 | "timestamp": timestamp, 106 | "new-view": int(tokens[6][:-1]), 107 | "new-timeout": round(float(tokens[10])), 108 | } 109 | 110 | def parse_reset_timeout(self, line, node_id): 111 | tokens = line.split() 112 | timestamp = round(float(tokens[1][1:-1])) 113 | 114 | return { 115 | "node": node_id, 116 | "type": "reset-timeout", 117 | "timestamp": timestamp, 118 | "view": int(tokens[8]), 119 | } 120 | 121 | def parse_enough_vote(self, line, node_id): 122 | tokens = line.split() 123 | timestamp = round(float(tokens[1][1:-1])) 124 | 125 | return { 126 | "node": node_id, 127 | "type": "enough-vote", 128 | "timestamp": timestamp, 129 | } 130 | 131 | def parse_events(self): 132 | events = [] 133 | for node_id in self.logs: 134 | for line in self.logs[node_id]: 135 | if "new view" in line: 136 | events.append(self.parse_new_view(line, node_id)) 137 | if "reset timeout" in line: 138 | events.append(self.parse_reset_timeout(line, node_id)) 139 | if "enough vote" in line: 140 | events.append(self.parse_enough_vote(line, node_id)) 141 | return events 142 | -------------------------------------------------------------------------------- /visualization/parsers/hotstuff.py: -------------------------------------------------------------------------------- 1 | from .base import BaseParser 2 | import json 3 | 4 | class HotStuffParser(BaseParser): 5 | def __init__(self, bft_dir): 6 | super().__init__(bft_dir) 7 | 8 | def parse(self): 9 | self.logs = self.load_logs() 10 | 11 | pkts = self.parse_packets() 12 | events = self.parse_events() 13 | 14 | return { 15 | "info": {"nodes": len(self.logs)}, 16 | "pkts": pkts, 17 | "events": events 18 | } 19 | 20 | def parse_send(self, line): 21 | tokens = line.split() 22 | timestamp = round(float(tokens[2][1:-1])) 23 | dst = tokens[3][1:-1] 24 | raw_data = line[line.find("{"):] 25 | data = json.loads(raw_data) 26 | 27 | return { 28 | "send_time": timestamp, 29 | "recv_time": -1, 30 | "src": int(data['src']), 31 | "dst": int(dst) if dst != "broadcast" else dst, 32 | "req": data['request'], 33 | "type": data['type'], 34 | "data": raw_data 35 | } 36 | 37 | def parse_recv(self, line): 38 | tokens = line.split() 39 | timestamp = round(float(tokens[2][1:-1])) 40 | raw_data = line[line.find("{"):] 41 | data = json.loads(raw_data) 42 | 43 | return { 44 | "recv_time": timestamp, 45 | "src": int(data['src']), 46 | "req": data["request"], 47 | "type": data["type"] 48 | } 49 | 50 | def parse_packets(self): 51 | pkts = [] 52 | src_dst_req_type_to_pkt = dict() 53 | src_dst_req_type_to_recv = dict() 54 | for node_id in self.logs: 55 | for line in self.logs[node_id]: 56 | is_send = "send" in line 57 | is_recv = "recv" in line 58 | is_protocol = "request" in line 59 | if (not is_send and not is_recv) or not is_protocol: 60 | continue 61 | 62 | if is_send: 63 | pkt = self.parse_send(line) 64 | if pkt['dst'] == 'broadcast': 65 | for i in range(1, len(self.logs) + 1): 66 | if i == node_id: 67 | continue 68 | new_pkt = pkt.copy() 69 | new_pkt['dst'] = i 70 | _key = f"{node_id}_{i}_{pkt['req']}_{pkt['type']}" 71 | if _key in src_dst_req_type_to_pkt: 72 | print(f"[Warning] duplicate packet: {_key}") 73 | src_dst_req_type_to_pkt[_key] = new_pkt 74 | else: 75 | _key = f"{node_id}_{pkt['dst']}_{pkt['req']}_{pkt['type']}" 76 | if _key in src_dst_req_type_to_pkt: 77 | print(f"[Warning] duplicate packet: {_key}") 78 | src_dst_req_type_to_pkt[_key] = pkt 79 | else: 80 | recv = self.parse_recv(line) 81 | _key = f"{recv['src']}_{node_id}_{recv['req']}_{recv['type']}" 82 | if _key in src_dst_req_type_to_recv: 83 | print(f"[Warning] {_key} has already been received") 84 | src_dst_req_type_to_recv[_key] = recv 85 | 86 | for _key, pkt in src_dst_req_type_to_pkt.items(): 87 | if _key not in src_dst_req_type_to_recv: 88 | print(f"[Warning] Missing recv pkt for {_key}") 89 | continue 90 | pkt['recv_time'] = src_dst_req_type_to_recv[_key]['recv_time'] 91 | pkts.append(pkt) 92 | del src_dst_req_type_to_recv[_key] 93 | 94 | if len(src_dst_req_type_to_recv) != 0: 95 | print(f"[Warning] {len(src_dst_req_type_to_recv)} receives don't have corresponding sending packets") 96 | 97 | return pkts 98 | 99 | def parse_new_view(self, line, node_id): 100 | tokens = line.split() 101 | timestamp = round(float(tokens[1][1:-1])) 102 | 103 | return { 104 | "node": node_id, 105 | "type": "new-view", 106 | "timestamp": timestamp, 107 | "new-view": int(tokens[6]), 108 | # "new-timeout": round(float(tokens[10])), 109 | } 110 | 111 | def parse_reset_timeout(self, line, node_id): 112 | tokens = line.split() 113 | timestamp = round(float(tokens[1][1:-1])) 114 | 115 | return { 116 | "node": node_id, 117 | "type": "reset-timeout", 118 | "timestamp": timestamp, 119 | "view": int(tokens[8]), 120 | } 121 | 122 | def parse_enough_vote(self, line, node_id): 123 | tokens = line.split() 124 | timestamp = round(float(tokens[1][1:-1])) 125 | 126 | return { 127 | "node": node_id, 128 | "type": "enough-vote", 129 | "timestamp": timestamp, 130 | } 131 | 132 | def parse_events(self): 133 | events = [] 134 | for node_id in self.logs: 135 | for line in self.logs[node_id]: 136 | if "new view" in line: 137 | events.append(self.parse_new_view(line, node_id)) 138 | if "reset timeout" in line: 139 | events.append(self.parse_reset_timeout(line, node_id)) 140 | if "enough vote" in line: 141 | events.append(self.parse_enough_vote(line, node_id)) 142 | return events 143 | -------------------------------------------------------------------------------- /simulator.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Logger = require('./lib/logger'); 4 | const Network = require('./network/network'); 5 | const FastPriorityQueue = require('fastpriorityqueue'); 6 | const ValidatorModule = require('./validator/audit_queue'); 7 | 8 | class Simulator { 9 | registerTimeEvent(functionMeta, waitTime, eventQ, nodeID) { 10 | eventQ.add({ 11 | type: 'time-event', 12 | functionMeta: functionMeta, 13 | dst: '' + nodeID, 14 | registeredTime: this.clock, 15 | triggeredTime: this.clock + waitTime 16 | }); 17 | } 18 | 19 | registerMsgEvent(packet, waitTime, eventQ) { 20 | eventQ.add({ 21 | type: 'msg-event', 22 | packet: packet, 23 | dst: packet.dst, 24 | registeredTime: this.clock, 25 | triggeredTime: this.clock + waitTime 26 | }); 27 | } 28 | 29 | registerAttackerTimeEvent(functionMeta, waitTime, eventQ) { 30 | eventQ.add({ 31 | type: 'attacker-time-event', 32 | functionMeta: functionMeta, 33 | registeredTime: this.clock, 34 | triggeredTime: this.clock + waitTime 35 | }); 36 | } 37 | 38 | startSimulation() { 39 | for (; this.network.attacker.updateParam() || this.simCount < this.config.repeatTime; this.simCount++) { 40 | this.runOnce(); 41 | this.reset(); 42 | } 43 | } 44 | 45 | runOnce() { 46 | for (let nodeID = 1; nodeID <= this.correctNodeNum; nodeID++) { 47 | this.nodes[nodeID] = new this.Node( 48 | '' + nodeID, 49 | this.nodeNum, 50 | this.network, 51 | // register time event 52 | (functionMeta, waitTime) => { 53 | return this.registerTimeEvent(functionMeta, waitTime, this.eventQ, nodeID) 54 | }, 55 | this.config, 56 | ); 57 | } 58 | 59 | this.network.addNodes(this.nodes); 60 | 61 | // main loop - run till one simulation ends 62 | while (!this.eventQ.isEmpty()) { 63 | // pop events that should be processed 64 | const waitingEvents = []; 65 | this.clock = this.eventQ.peek().triggeredTime; 66 | while (!this.eventQ.isEmpty() && this.eventQ.peek().triggeredTime === this.clock) 67 | waitingEvents.push(this.eventQ.poll()); 68 | this.eventQ.trim(); 69 | 70 | waitingEvents.forEach((e) => { 71 | switch (e.type) { 72 | case 'msg-event': 73 | this.nodes[e.dst].onMsgEvent(e); break; 74 | case 'time-event': 75 | this.nodes[e.dst].onTimeEvent(e); break; 76 | case 'attacker-time-event': 77 | this.network.attacker.onTimeEvent(e); break; 78 | } 79 | }); 80 | 81 | if (this.onEventsProccessed) this.onEventsProccessed(); 82 | if (this.judge()) return this.decided(); 83 | } 84 | console.log("Error! eventQ is empty before simulation ends!"); 85 | } 86 | 87 | // judge determines whether a consensus is reached or not 88 | judge() { 89 | let decideCount = 0; 90 | for (let nodeID = 1; nodeID <= this.correctNodeNum; nodeID++) { 91 | if (this.nodes[nodeID].isDecided) { 92 | decideCount += 1; 93 | } 94 | } 95 | 96 | return decideCount >= this.majority; 97 | } 98 | 99 | decided() { 100 | this.simulationResults.push({ 101 | latency: this.clock, 102 | msgBytes: this.network.totalMsgBytes, 103 | msgCount: this.network.msgCount, 104 | totalMsgCount: this.network.totalMsgCount, 105 | }); 106 | if (this.onDecision) this.onDecision(); 107 | } 108 | 109 | reset() { 110 | this.eventQ.removeMany(() => true); 111 | this.eventQ.trim(); 112 | this.clock = 0; 113 | this.nodes = {}; 114 | this.network.removeNodes(); 115 | } 116 | 117 | startValidator() { 118 | this.simCount++; 119 | this.auditor = new ValidatorModule(this.config.validatorLogPath, 120 | // send to system 121 | () => {} 122 | ); 123 | // load ground truth. 124 | this.auditor.logFromFile(); 125 | 126 | for (let nodeID = 1; nodeID <= this.correctNodeNum; nodeID++) { 127 | this.nodes[nodeID] = new this.Node( 128 | '' + nodeID, 129 | this.nodeNum, 130 | // auditor would mock a network that simply saves all packets. 131 | this.auditor.network, 132 | // register time event 133 | (functionMeta, waitTime) => { 134 | this.eventQ.add({ 135 | type: 'time-event', 136 | functionMeta: functionMeta, 137 | dst: '' + nodeID, 138 | registeredTime: this.clock, 139 | triggeredTime: this.clock + waitTime 140 | }); 141 | } 142 | ); 143 | if (nodeID === this.correctNodeNum) { 144 | this.auditor.network.addNodes(this.nodes); 145 | } 146 | } 147 | 148 | // main loop 149 | while (true) { 150 | const timeEvents = []; 151 | let nextMsgEvent = this.auditor.nextMsgEvent(); 152 | if (nextMsgEvent !== null ){ 153 | this.nodes[nextMsgEvent.dst].onMsgEvent(nextMsgEvent); 154 | } else { 155 | // if there's no matched msgevent then trigger the time event. 156 | this.clock = this.eventQ.peek().triggeredTime; 157 | console.log("triggering event", this.eventQ.peek()); 158 | const msgEvents = []; 159 | while (!this.eventQ.isEmpty() && 160 | this.eventQ.peek().triggeredTime === this.clock) { 161 | const event = this.eventQ.poll(); 162 | switch (event.type) { 163 | // there should only be time event. 164 | case 'msg-event': 165 | msgEvents.push(event); 166 | break; 167 | case 'time-event': 168 | timeEvents.push(event); 169 | break; 170 | case 'attacker-time-event': 171 | attackerTimeEvents.push(event); 172 | } 173 | } 174 | console.log(`there's ${timeEvents.length} time events`); 175 | timeEvents.forEach((event) => { 176 | console.log(event); 177 | this.nodes[event.dst].onTimeEvent(event); 178 | }); 179 | } 180 | this.judge(); 181 | } 182 | 183 | } 184 | 185 | constructor(config) { 186 | Logger.clearLogDir(); 187 | this.eventQ = new FastPriorityQueue((eventA, eventB) => { 188 | return eventA.triggeredTime < eventB.triggeredTime; 189 | }); 190 | this.config = config; 191 | this.clock = 0; 192 | this.simCount = 0; 193 | this.Node = require(`./ba-algo/${config.protocol}`); 194 | this.nodes = {}; 195 | this.nodeNum = config.nodeNum; 196 | this.byzantineNodeNum = config.byzantineNodeNum; 197 | this.correctNodeNum = this.nodeNum - this.byzantineNodeNum; 198 | this.majority = this.nodeNum - Math.floor((this.nodeNum - 1) / 3); 199 | this.simulationResults = []; 200 | 201 | // callback functions 202 | this.onEventsProccessed = undefined; 203 | this.onDecision = undefined; 204 | 205 | this.network = new Network( 206 | // send to system 207 | () => {}, 208 | // register msg event 209 | (packet, waitTime) => { 210 | this.eventQ.add({ 211 | type: 'msg-event', 212 | packet: packet, 213 | dst: packet.dst, 214 | registeredTime: this.clock, 215 | triggeredTime: this.clock + waitTime 216 | }); 217 | }, 218 | // register attacker time event 219 | (functionMeta, waitTime) => { 220 | return this.registerAttackerTimeEvent(functionMeta, waitTime, this.eventQ) 221 | }, 222 | this.eventQ, 223 | this.nodeNum, 224 | this.byzantineNodeNum, 225 | // get clock 226 | () => this.clock, 227 | config 228 | ); 229 | } 230 | }; 231 | 232 | module.exports = Simulator; 233 | -------------------------------------------------------------------------------- /ba-algo/async-BA.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const uuid = require('uuid/v4'); 4 | const Node = require('./node'); 5 | 6 | class ABANode extends Node { 7 | // count of an element in an array 8 | getCount(a, v) { 9 | if (a === undefined || a.length === 0) { 10 | return 0 11 | } 12 | const valueMap = {}; 13 | data.forEach(msg => { 14 | if (valueMap[msg.value] === undefined) { 15 | valueMap[msg.value] = 1; 16 | } 17 | else { 18 | valueMap[msg.value]++; 19 | } 20 | }); 21 | let maxValue = undefined; 22 | let maxCount = 0; 23 | for (let value in valueMap) { 24 | if (valueMap[value] > maxCount) { 25 | maxCount = valueMap[value]; 26 | maxValue = value; 27 | } 28 | } 29 | return { value: maxValue, count: maxCount }; 30 | } 31 | // broadcast via 2pc 32 | broadcast2pc(v) { 33 | const initMsg = { 34 | type: 'init', 35 | sender: this.nodeID, 36 | v: v 37 | }; 38 | this.send(this.nodeID, 'broadcast', initMsg); 39 | /* 40 | const echoMsg = { 41 | type: 'echo', 42 | sender: this.nodeID, 43 | v: v 44 | }*/ 45 | //this.send(this.nodeID, 'broadcast', echoMsg); 46 | this.vBox[v.ID] = { 47 | init: [initMsg], 48 | echo: [], 49 | ready: [], 50 | v: v, 51 | step: 1, 52 | accept: false 53 | }; 54 | } 55 | // receive via 2pc 56 | receive2pc(msg) { 57 | this.logger.warning(['accept', JSON.stringify(msg)]); 58 | function getMaxMsgV(msgArray) { 59 | if (msgArray === undefined || msgArray.length === 0) { 60 | return { value: undefined, count: 0 }; 61 | } 62 | const valueMap = {}; 63 | msgArray.forEach(msg => { 64 | if (valueMap[msg.value] === undefined) { 65 | valueMap[msg.value] = 1; 66 | } 67 | else { 68 | valueMap[msg.value]++; 69 | } 70 | }); 71 | let maxValue = undefined; 72 | let maxCount = 0; 73 | for (let value in valueMap) { 74 | if (valueMap[value] > maxCount) { 75 | maxCount = valueMap[value]; 76 | maxValue = value; 77 | } 78 | } 79 | return { value: maxValue, count: maxCount }; 80 | } 81 | // validate should be added 82 | if (this.valids[msg.k] === undefined) { 83 | this.valids[msg.k] = [msg]; 84 | } 85 | else { 86 | this.valids[msg.k].push(msg); 87 | } 88 | let k = 3 * this.phase + this.round; 89 | if (k !== msg.k) { 90 | return; 91 | } 92 | while (this.valids[k].length >= 2 * this.f + 1) { 93 | let maxV = getMaxMsgV(this.valids[k]); 94 | switch (this.round) { 95 | case 1: 96 | this.valueP = maxV.value; 97 | this.round++; 98 | this.broadcast2pc({ 99 | k: 3 * this.phase + this.round, 100 | sender: this.nodeID, 101 | value: this.valueP, 102 | ID: uuid() 103 | }); 104 | this.logger.warning(['' + this.round]); 105 | 106 | break; 107 | case 2: 108 | // this param is f + 1 or N / 2 ? 109 | if (maxV.count >= //this.f + 1) { 110 | Math.floor(this.nodeNum / 2) + 1) { 111 | this.valueP = { v: maxV.value, d: true }; 112 | } 113 | this.round++; 114 | this.broadcast2pc({ 115 | k: 3 * this.phase + this.round, 116 | sender: this.nodeID, 117 | value: JSON.stringify(this.valueP), 118 | ID: uuid() 119 | }); 120 | break; 121 | case 3: 122 | const value = JSON.parse(maxV.value); 123 | // value = {v: 0, d: true} or 0 124 | if (value.d === true && maxV.count >= 2 * this.f + 1) { 125 | this.valueP = value.v; 126 | this.decidedValue = this.valueP; 127 | this.isDecided = true; 128 | } 129 | else if (value.d === true && maxV.count >= this.f + 1) { 130 | this.valueP = value.v; 131 | } 132 | else { 133 | this.valueP = Math.round(Math.random()); 134 | } 135 | this.round = 1; 136 | this.phase++; 137 | this.broadcast2pc({ 138 | k: 3 * this.phase + this.round, 139 | sender: this.nodeID, 140 | value: this.valueP, 141 | ID: uuid() 142 | }); 143 | break; 144 | default: 145 | this.logger.warning(['Undefined round.']); 146 | } 147 | k = 3 * this.phase + this.round; 148 | if (this.valids[k] === undefined) { 149 | this.valids[k] = []; 150 | break; 151 | } 152 | } 153 | } 154 | // receive from network 155 | onMsgEvent(msgEvent) { 156 | super.onMsgEvent(msgEvent); 157 | const msg = msgEvent.packet.content; 158 | this.logger.info(['recv', JSON.stringify(msg)]); 159 | const v = msg.v; 160 | if (this.vBox[v.ID] === undefined) { 161 | this.vBox[v.ID] = { 162 | init: [], 163 | echo: [], 164 | ready: [], 165 | v: v, 166 | step: 1, 167 | accept: false 168 | }; 169 | } 170 | this.vBox[v.ID][msg.type].push(msg); 171 | switch (this.vBox[v.ID].step) { 172 | case 1: 173 | const echoMsg = { 174 | type: 'echo', 175 | sender: this.nodeID, 176 | v: v 177 | }; 178 | if (this.vBox[v.ID].init.length >= 1 || 179 | this.vBox[v.ID].echo.length >= 2 * this.f + 1 || 180 | this.vBox[v.ID].ready.length >= this.f + 1) { 181 | this.vBox[v.ID].step = 2; 182 | this.vBox[v.ID].echo.push(echoMsg); 183 | this.send(this.nodeID, 'broadcast', echoMsg); 184 | } 185 | break; 186 | case 2: 187 | const readyMsg = { 188 | type: 'ready', 189 | sender: this.nodeID, 190 | v: v 191 | }; 192 | if (this.vBox[v.ID].echo.length >= 2 * this.f + 1 || 193 | this.vBox[v.ID].ready.length >= this.f + 1) { 194 | this.vBox[v.ID].step = 3; 195 | this.vBox[v.ID].ready.push(readyMsg); 196 | this.send(this.nodeID, 'broadcast', readyMsg); 197 | } 198 | break; 199 | case 3: 200 | if (this.vBox[v.ID].ready.length >= this.f + 1 && 201 | !this.vBox[v.ID].accept) { 202 | this.vBox[v.ID].accept = true; 203 | this.receive2pc(v); 204 | } 205 | break; 206 | default: 207 | this.logger.warning(['Undefined step.']); 208 | } 209 | } 210 | 211 | onTimeEvent(timeEvent) { 212 | super.onTimeEvent(timeEvent); 213 | this.broadcast2pc(this.initV); 214 | } 215 | 216 | constructor(nodeID, nodeNum, network, registerTimeEvent) { 217 | super(nodeID, nodeNum, network, registerTimeEvent); 218 | this.f = (this.nodeNum % 3 === 0) ? 219 | this.nodeNum / 3 - 1 : Math.floor(this.nodeNum / 3); 220 | // 2 phase commit 221 | // v.ID => { initCount, readyCount, echoCount, v } 222 | this.vBox = {}; 223 | // BA 224 | // round => array 225 | this.valids = []; 226 | this.isDecided = false; 227 | this.decidedValue = undefined; 228 | this.phase = 0; 229 | this.round = 1; 230 | // start BA process 231 | // propose init value 232 | this.initValue = '' + Math.round(Math.random()); 233 | this.initV = { 234 | k: 3 * this.phase + this.round, 235 | sender: this.nodeID, 236 | value: this.initValue, 237 | ID: uuid() 238 | }; 239 | this.registerTimeEvent({ 240 | name: 'broadcast2pc' 241 | }, 0); 242 | } 243 | } 244 | //const n = new ABANode(process.argv[2], process.argv[3]); 245 | module.exports = ABANode; 246 | -------------------------------------------------------------------------------- /ba-algo/hotstuff-NS.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('./node'); 4 | const uuid = require('uuid/v4'); 5 | let config = require('../config'); 6 | 7 | const msgType = { 8 | vote: 'hot-stuff-vote', 9 | proposal: 'hot-stuff-proposal' 10 | } 11 | const eventType = { 12 | start: 'start', 13 | nextViewInterrupt: 'hot-stuff-next-view-interrupt', 14 | } 15 | 16 | const extendVector = (v, n) => { if (v[n] === undefined) v[n] = []; } 17 | 18 | class HotStuffNode extends Node { 19 | 20 | // util 21 | 22 | newQC = (request, view, height, signers) => ({ 23 | request, view, height, signers 24 | }); 25 | newProposal = (height, view, src, request, QC, primary, dummyBlocks, parent) => ({ 26 | type: msgType.proposal, height, view, src, request, QC, primary, dummyBlocks, parent 27 | }); 28 | newVote = (view, src, request, QC) => ({ 29 | type: msgType.vote, view, src, request, QC 30 | }); 31 | 32 | insertBlock(block) { 33 | if (block.dummyBlocks !== undefined && block.dummyBlocks.length > 0) { 34 | block.dummyBlocks.forEach(dummyBlock => { 35 | this.logger.info(['insert dummy', JSON.stringify(dummyBlock)]); 36 | this.insertBlock(dummyBlock); 37 | }); 38 | } 39 | 40 | this.logger.info(['inserting-block', JSON.stringify(block)]) 41 | this.blocks[block.request] = block; 42 | if (!this.heightToBlock[block.height]) this.heightToBlock[block.height] = block.request; 43 | } 44 | 45 | castVote = (vote) => { 46 | extendVector(this.ballots, vote.request); 47 | if (this.ballots[vote.request].every(m => m.src !== vote.src)) { 48 | this.ballots[vote.request].push(vote); 49 | return true; 50 | } 51 | return false; 52 | } 53 | 54 | getBlockVotesNum = (req) => this.ballots[req] ? this.ballots[req].length : 0; 55 | 56 | generateQC(block) { 57 | let signers = this.ballots[block.request].map(m => m.src); 58 | return this.newQC(block.request, block.view, block.height, signers); 59 | } 60 | 61 | generateDummyBlock(QC, height) { 62 | let parent = QC.request; 63 | let dummyBlocks = []; 64 | for (let h = QC.height + 1; v <= height; v++) { 65 | let block = this.newProposal(h, this.view, this.nodeID, uuid(), QC, this.nodeID, [], parent); 66 | dummyBlocks.push(block); 67 | parent = block.request; 68 | } 69 | return dummyBlocks.reverse(); 70 | } 71 | 72 | isAncestor(block, root) { 73 | let curBlock = block; 74 | while (curBlock.height > root.height) { 75 | let nextBlock = this.blocks[curBlock.parent]; 76 | if (nextBlock === undefined) { 77 | this.logger.info(['missing-parent-block', JSON.stringify(curBlock)]); 78 | return false; 79 | } 80 | curBlock = nextBlock; 81 | } 82 | return curBlock.height === root.height && curBlock.request === root.request; 83 | } 84 | 85 | // core protocol (leader) 86 | 87 | proposeNextRequest() { 88 | let parent = this.heightToBlock[this.vheight]; 89 | let dummyBlocks; 90 | if (parent === undefined) { 91 | dummyBlocks = this.generateDummyBlock(this.highQC, this.vheight); 92 | if (dummyBlocks.length > 0) { 93 | parent = dummyBlocks[0].request; 94 | } 95 | } 96 | 97 | const proposal = this.newProposal( 98 | this.vheight+1, this.view, this.nodeID, uuid(), this.highQC, this.nodeID, dummyBlocks, parent 99 | ); 100 | this.voteOnBlock(proposal); 101 | 102 | this.send(this.nodeID, 'broadcast', proposal); 103 | this.updateBlock(proposal); 104 | } 105 | 106 | receiveVote(vote) { 107 | if (vote.height < this.vheight) return; 108 | 109 | const block = this.blocks[vote.request]; 110 | if (this.castVote(vote) && this.getBlockVotesNum(block.request) === this.nodeNum - this.f) { 111 | this.logger.info([`${Math.round(this.clock)}`, 'enough vote', JSON.stringify(vote)]); 112 | const QC = this.generateQC(block); 113 | this.updateQCHigh(QC); 114 | if (this.isPrimary(this.view)) this.proposeNextRequest(); 115 | } 116 | } 117 | 118 | // core protocol (replica) 119 | 120 | safeNode = (msg) => msg.QC.height > this.lockedQC.height || this.isAncestor(msg, this.lockedQC); 121 | 122 | onReceiveProposal(proposal) { 123 | this.updateBlock(proposal); 124 | if (proposal.view !== this.view) { 125 | this.logger.warning(["Received a proposal not from the current leader"]); 126 | return; 127 | } 128 | if (proposal.height <= this.vheight) { 129 | this.logger.warning(["Received a proposal before current height"]); 130 | return; 131 | } 132 | if (this.safeNode(proposal)) this.voteOnBlock(proposal); 133 | } 134 | 135 | voteOnBlock(proposal) { 136 | const vote = this.newVote(proposal.view, this.nodeID, proposal.request, proposal.QC); 137 | this.castVote(vote); 138 | if (this.nodeID !== this.getPrimary(proposal.view)) { 139 | this.send(this.nodeID, this.getPrimary(proposal.view), vote); 140 | } 141 | this.vheight = proposal.height; 142 | } 143 | 144 | updateBlock(proposal) { 145 | this.insertBlock(proposal); 146 | if (proposal.QC === undefined) { 147 | return false; 148 | } 149 | 150 | this.updateQCHigh(proposal.QC); 151 | 152 | let parentBlock = this.blocks[proposal.QC.request]; 153 | if (parentBlock === undefined || parentBlock.QC === undefined) { 154 | return false; 155 | } 156 | this.updateLockQC(parentBlock.QC); 157 | 158 | let grandParentBlock = this.blocks[parentBlock.QC.request]; 159 | if (grandParentBlock === undefined || grandParentBlock.QC === undefined || 160 | grandParentBlock.parent !== grandParentBlock.QC.request || 161 | parentBlock.parent !== parentBlock.QC.request) { 162 | // Do not commit the block if it doesn't form a three-chained 163 | return false; 164 | } 165 | 166 | // decide 167 | this.commitBlock(grandParentBlock.QC.request); 168 | this.lastExecHeight = grandParentBlock.QC.height; 169 | } 170 | 171 | commitBlock(request) { 172 | this.logger.info([`Commit ${request}`]); 173 | const block = this.blocks[request]; 174 | if (block === undefined) { 175 | this.logger.info(['missing-block', 'decide', request]); 176 | return; 177 | } 178 | if (this.lastExecHeight < block.height) { 179 | // recursivly commit parent blocks 180 | if (block.parent) this.commitBlock(block.parent); 181 | 182 | this.logger.info(['decide', JSON.stringify(block)]); 183 | this.decideCount++; 184 | if (this.decideCount >= 100) this.isDecided = true; 185 | this.executeTimeout = this.lambda; 186 | this.logger.info([`${Math.round(this.clock)}`, `Node ${this.nodeID} reset timeout at view ${this.view}`]); 187 | this.registerNewNextViewInterrupt(); 188 | } 189 | } 190 | 191 | updateQCHigh(QC) { 192 | if (this.highQC === this.GenesisQC || QC.height > this.highQC.height) { 193 | this.highQC = QC; 194 | } 195 | } 196 | 197 | updateLockQC(QC) { 198 | if (this.lockedQC === this.GenesisQC || QC.height > this.lockedQC.height) { 199 | this.lockedQC = QC; 200 | this.logger.info(['locked-QC', JSON.stringify(QC)]); 201 | } 202 | } 203 | 204 | // pacemaker 205 | 206 | registerNewNextViewInterrupt() { 207 | this.currNextViewInterrupt = uuid(); 208 | this.registerTimeEvent({ 209 | name: eventType.nextViewInterrupt, 210 | params: { uuid: this.currNextViewInterrupt } 211 | }, 212 | this.executeTimeout * 1000 213 | ); 214 | } 215 | 216 | viewChange() { 217 | this.view++; 218 | this.executeTimeout *= 2; 219 | this.logger.info([`${Math.round(this.clock)}`, `enter a new view ${this.view}, doubling timeout to ${this.executeTimeout}`]); 220 | this.registerNewNextViewInterrupt(); 221 | 222 | if (this.isPrimary(this.view)) return this.proposeNextRequest(); 223 | } 224 | 225 | getPrimary = (view) => `${(view % this.nodeNum) + 1}`; 226 | isPrimary = (view) => this.getPrimary(view) === this.nodeID; 227 | 228 | // simulator related API 229 | 230 | onMsgEvent(msgEvent) { 231 | super.onMsgEvent(msgEvent); 232 | const msg = msgEvent.packet.content; 233 | this.logger.info(['recv', 234 | this.logger.round(msgEvent.triggeredTime), 235 | JSON.stringify(msg) 236 | ]); 237 | switch (msg.type) { 238 | case msgType.vote: 239 | return this.receiveVote(msg); 240 | case msgType.proposal: 241 | return this.onReceiveProposal(msg); 242 | default: 243 | this.logger.warning(['undefined msg type']); 244 | } 245 | } 246 | 247 | onTimeEvent(timeEvent) { 248 | super.onTimeEvent(timeEvent); 249 | const meta = timeEvent.functionMeta; 250 | switch (meta.name) { 251 | case eventType.nextViewInterrupt: 252 | if (this.currNextViewInterrupt !== meta.params.uuid) break; 253 | this.viewChange(); 254 | break; 255 | case 'start': 256 | if (this.isPrimary(this.view)) this.proposeNextRequest(); 257 | break; 258 | default: 259 | console.log('undefined function name'); 260 | process.exit(0); 261 | } 262 | } 263 | 264 | constructor(nodeID, nodeNum, network, registerTimeEvent, customized_config) { 265 | super(nodeID, nodeNum, network, registerTimeEvent); 266 | if (customized_config !== undefined) { 267 | config = customized_config; 268 | } 269 | this.f = Math.floor((this.nodeNum - 1) / 3); 270 | 271 | this.lambda = config.lambda; // base timeout of the view-doubling synchronizer 272 | this.executeTimeout = this.lambda; 273 | 274 | this.view = 0; 275 | this.lastExecHeight = 0; 276 | 277 | this.GenesisQC = this.newQC('hot-stuff-genesis-null-QC', 0, 0, []) 278 | this.lockedQC = this.GenesisQC; 279 | this.highQC = this.GenesisQC; 280 | 281 | this.isDecided = false; 282 | this.decideCount = 0; 283 | this.ballots = {}; 284 | this.isVoted = {}; 285 | this.blocks = {}; 286 | this.heightToBlock = {}; 287 | this.vheight = 0; 288 | 289 | this.insertBlock(this.GenesisQC); 290 | this.nextView = {}; 291 | this.currNextViewInterrupt = undefined; 292 | this.registerNewNextViewInterrupt(); 293 | 294 | this.registerTimeEvent({ name: 'start', params: {} }, 0); 295 | } 296 | } 297 | 298 | module.exports = HotStuffNode; 299 | -------------------------------------------------------------------------------- /ba-algo/vmware-ba/vrf.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('../node'); 4 | const config = require('../../config'); 5 | const uuid = require('uuid/v4'); 6 | 7 | class VMwareNode extends Node { 8 | 9 | // extend vector v to be able to access v[n] = array 10 | extendVector(v, n) { 11 | if (v[n] === undefined) { 12 | v[n] = []; 13 | } 14 | } 15 | 16 | decide(v) { 17 | //clearTimeout(this.BALogicTimer); 18 | this.logger.info([`decide on ${v}`]); 19 | this.isDecided = true; 20 | this.decidedValue = v; 21 | } 22 | 23 | runBALogic(round) { 24 | switch (round) { 25 | case 1: 26 | // end of notify and start of status 27 | this.extendVector(this.notify, this.k); 28 | if (this.notify[this.k].length > 0) { 29 | const msg = this.notify[this.k][0]; 30 | this.accepted.vi = msg.header.v; 31 | this.accepted.Ci = msg.Ci; 32 | this.accepted.ki = this.k; 33 | }; 34 | this.k++; 35 | const statusMsg = { 36 | sender: this.nodeID, 37 | type: 'status', 38 | k: this.k, 39 | vi: this.accepted.vi, 40 | ki: this.accepted.ki, 41 | Ci: this.accepted.Ci 42 | }; 43 | this.status.push(statusMsg); 44 | this.send(this.nodeID, 'broadcast', statusMsg); 45 | this.registerTimeEvent( 46 | { name: 'runBALogic', params: { round: 2 } }, 47 | 2 * config.lambda * 1000 48 | ); 49 | break; 50 | case 2: 51 | // end of status and start of propose 52 | this.accepted.vi = uuid(); 53 | this.accepted.ki = 0; 54 | this.accepted.Ci = 'undefined'; 55 | if (this.status.length > 0) { 56 | const msg = this.status 57 | .groupBy(msg => msg.ki) 58 | // [['ki', [status msg]], ['ki', [status msg]]] 59 | .maxBy(arr => parseInt(arr[0]))[1][0]; 60 | if (msg.Ci !== 'undefined') { 61 | this.accepted.vi = msg.vi; 62 | this.accepted.ki = msg.ki; 63 | this.accepted.Ci = msg.Ci; 64 | } 65 | } 66 | const proposeMsg = { 67 | sender: this.nodeID, 68 | type: 'fl-propose', 69 | proposeMsg: { 70 | sender: this.nodeID, 71 | k: this.k, 72 | type: 'propose', 73 | vL: this.accepted.vi, 74 | // VRF 75 | y: Math.floor(Math.random() * 1000000000 + 1) 76 | }, 77 | kL: this.accepted.ki, 78 | CL: this.accepted.Ci 79 | }; 80 | this.send(this.nodeID, 'broadcast', proposeMsg); 81 | this.flPropose.push(proposeMsg); 82 | this.status = []; 83 | this.registerTimeEvent( 84 | { name: 'runBALogic', params: { round: 3 } }, 85 | 2 * config.lambda * 1000 86 | ); 87 | /* 88 | this.BALogicTimer = setTimeout(() => { 89 | this.runBALogic(3); 90 | }, 2 * config.lambda * 1000);*/ 91 | break; 92 | case 3: 93 | // end of propose and start of commit 94 | // remove duplicate leader proposal 95 | this.flPropose = this.flPropose 96 | .groupBy(msg => msg.sender) 97 | // [[sender, [msg]], [sender, [msg]]] 98 | .filter(arr => arr[1].length <= 1) 99 | .map(arr => arr[1]) 100 | // [[msg], [msg]] 101 | .flat(); 102 | this.flPropose.sort((msgA, msgB) => { 103 | if (msgA.kL < msgB.kL) { 104 | return 1; 105 | } 106 | else if (msgA.kL > msgB.kL) { 107 | return -1; 108 | } 109 | else { 110 | return (msgA.proposeMsg.y < msgB.proposeMsg.y) ? 1 : -1; 111 | } 112 | }); 113 | const bestProposal = this.flPropose[0]; 114 | if (bestProposal === undefined || bestProposal.kL < this.accepted.ki) { 115 | // leader is faulty or no leader 116 | this.vLi = 'undefined'; 117 | } 118 | else { 119 | this.proposeMsg = bestProposal.proposeMsg; 120 | this.vLi = this.proposeMsg.vL; 121 | } 122 | if (this.vLi !== 'undefined') { 123 | // forward leader propose 124 | this.send(this.nodeID, 'broadcast', this.proposeMsg); 125 | const commitMsg = { 126 | sender: this.nodeID, 127 | k: this.k, 128 | type: 'commit', 129 | vLi: this.vLi, 130 | y: this.proposeMsg.y 131 | }; 132 | this.send(this.nodeID, 'broadcast', commitMsg); 133 | this.commit.push(commitMsg); 134 | } 135 | this.flPropose = []; 136 | this.registerTimeEvent( 137 | { name: 'runBALogic', params: { round: 4 } }, 138 | 2 * config.lambda * 1000 139 | ); 140 | /* 141 | this.BALogicTimer = setTimeout(() => { 142 | this.runBALogic(4); 143 | }, 2 * config.lambda * 1000);*/ 144 | break; 145 | case 4: 146 | // end of commit and start of notify 147 | if (this.propose.some(msg => 148 | msg.k === this.k && msg.vL !== this.vLi)) { 149 | // leader has equivocated 150 | // do not commit 151 | this.logger.warning(['leader has equivocated']); 152 | } 153 | else { 154 | const C = this.commit.filter( 155 | msg => msg.vLi === this.vLi && msg.k === this.k); 156 | if (C.length >= this.nodeNum - this.f) { 157 | this.accepted.vi = this.vLi; 158 | this.accepted.Ci = C; 159 | const proof = 160 | JSON.parse(JSON.stringify(C)).splice(0, this.nodeNum - this.f); 161 | const notifyMsg = { 162 | sender: this.nodeID, 163 | type: 'notify', 164 | header: { 165 | sender: this.nodeID, 166 | type: 'notify-header', 167 | v: this.vLi 168 | }, 169 | Ci: proof 170 | }; 171 | this.send(this.nodeID, 'broadcast', notifyMsg); 172 | const k = notifyMsg.Ci[0].k; 173 | this.extendVector(this.notify, k); 174 | this.notify[k].push(notifyMsg); 175 | } 176 | } 177 | this.propose = []; 178 | this.commit = []; 179 | this.vLi = 'undefined'; 180 | this.registerTimeEvent( 181 | { name: 'runBALogic', params: { round: 1 } }, 182 | 2 * config.lambda * 1000 183 | ); 184 | /* 185 | this.BALogicTimer = setTimeout(() => { 186 | this.runBALogic(1); 187 | }, 2 * config.lambda * 1000);*/ 188 | break; 189 | default: 190 | this.logger.warning(['unknown round']); 191 | } 192 | 193 | } 194 | 195 | onMsgEvent(msgEvent) { 196 | super.onMsgEvent(msgEvent); 197 | const msg = msgEvent.packet.content; 198 | this.logger.info(['recv', this.logger.round(msgEvent.triggeredTime), JSON.stringify(msg)]); 199 | if (this.isDecided) { 200 | return; 201 | } 202 | switch(msg.type) { 203 | case 'status': 204 | // verify msg.Ci 205 | this.status.push(msg); 206 | break; 207 | case 'fl-propose': 208 | this.flPropose.push(msg); 209 | break; 210 | case 'propose': 211 | this.propose.push(msg); 212 | break; 213 | case 'commit': 214 | this.commit.push(msg); 215 | break; 216 | case 'notify': 217 | const k = msg.Ci[0].k; 218 | this.extendVector(this.notify, k); 219 | this.notify[k].push(msg); 220 | if (this.notify[k].length >= this.f + 1) { 221 | const headers = this.notify[k] 222 | .map(notifyMsg => notifyMsg.header); 223 | const headerMsg = { 224 | sender: this.nodeID, 225 | type: 'notify-headers', 226 | headers: headers 227 | }; 228 | this.send(this.nodeID, 'broadcast', headerMsg); 229 | this.decide(headers[0].v); 230 | } 231 | break; 232 | case 'notify-headers': 233 | // sanity check 234 | const headerMsg = { 235 | sender: this.nodeID, 236 | type: 'notify-headers', 237 | headers: msg.headers 238 | }; 239 | this.send(this.nodeID, 'broadcast', headerMsg); 240 | this.decide(msg.headers[0].v); 241 | break; 242 | default: 243 | this.logger.warning(['unknown message type']); 244 | } 245 | } 246 | 247 | onTimeEvent(timeEvent) { 248 | super.onTimeEvent(timeEvent); 249 | if (this.isDecided) { 250 | return; 251 | } 252 | const functionMeta = timeEvent.functionMeta; 253 | switch (functionMeta.name) { 254 | case 'start': 255 | const initStatusMsg = { 256 | sender: this.nodeID, 257 | type: 'status', 258 | k: this.k, 259 | vi: this.accepted.vi, 260 | ki: this.accepted.ki, 261 | Ci: this.accepted.Ci 262 | }; 263 | this.status.push(initStatusMsg); 264 | this.send(this.nodeID, 'broadcast', initStatusMsg); 265 | this.registerTimeEvent( 266 | { name: 'runBALogic', params: { round: 2 } }, 267 | 2 * config.lambda * 1000 268 | ); 269 | break; 270 | case 'runBALogic': 271 | this.runBALogic(functionMeta.params.round); 272 | break; 273 | } 274 | } 275 | 276 | constructor(nodeID, nodeNum, network, registerTimeEvent) { 277 | super(nodeID, nodeNum, network, registerTimeEvent); 278 | //this.isCooling = false; 279 | this.f = (this.nodeNum % 2 === 0) ? 280 | this.nodeNum / 2 - 1 : (this.nodeNum - 1) / 2; 281 | 282 | // BA related 283 | // store all accepted 284 | this.accepteds = []; 285 | this.accepted = { 286 | vi: 'undefined', 287 | ki: 0, 288 | Ci: 'undefined' 289 | }; 290 | this.k = 1; 291 | this.vLi = 'undefined'; 292 | this.leader; 293 | this.status = []; 294 | this.flPropose = []; 295 | this.propose = []; 296 | this.commit = []; 297 | this.notify = []; 298 | this.isDecided = false; 299 | this.decidedValue = undefined; 300 | 301 | this.registerTimeEvent({ name: 'start', params: {} }, 0); 302 | /* 303 | const targetStartTime = process.argv[4]; 304 | setTimeout(() => { 305 | this.send(this.nodeID, 'broadcast', initStatusMsg); 306 | // go to round 2 after 2l 307 | setTimeout(() => { 308 | this.runBALogic(2); 309 | }, 2 * config.lambda * 1000); 310 | }, targetStartTime - Date.now());*/ 311 | } 312 | } 313 | //const n = new VMwareNode(process.argv[2], process.argv[3]); 314 | module.exports = VMwareNode; -------------------------------------------------------------------------------- /ba-algo/vmware-ba/basic.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('../node'); 4 | const config = require('../../config'); 5 | const uuid = require('uuid/v4'); 6 | 7 | class VMwareNode extends Node { 8 | 9 | // extend vector v to be able to access v[n] = array 10 | extendVector(v, n) { 11 | if (v[n] === undefined) { 12 | v[n] = []; 13 | } 14 | } 15 | 16 | decide(v) { 17 | //clearTimeout(this.BALogicTimer); 18 | this.logger.info([`decide on ${v}`]); 19 | this.isDecided = true; 20 | this.decidedValue = v; 21 | } 22 | 23 | runBALogic(round) { 24 | switch (round) { 25 | case 1: 26 | // end of notify and start of status 27 | this.extendVector(this.notify, this.k); 28 | if (this.notify[this.k].length > 0) { 29 | const msg = this.notify[this.k][0]; 30 | this.accepted.vi = msg.header.v; 31 | this.accepted.Ci = msg.Ci; 32 | this.accepted.ki = this.k; 33 | }; 34 | this.status = []; 35 | this.propose = []; 36 | this.commit = []; 37 | this.k++; 38 | this.leader = '' + (this.k % this.nodeNum + 1); 39 | const statusMsg = { 40 | sender: this.nodeID, 41 | k: this.k, 42 | type: 'status', 43 | vi: this.accepted.vi, 44 | ki: this.accepted.ki, 45 | Ci: this.accepted.Ci 46 | }; 47 | if (this.nodeID === this.leader) { 48 | this.status.push(statusMsg); 49 | } 50 | else { 51 | this.send(this.nodeID, this.leader, statusMsg); 52 | } 53 | this.registerTimeEvent( 54 | { name: 'runBALogic', params: { round: 2 } }, 55 | 2 * config.lambda * 1000 56 | ); 57 | /* 58 | this.BALogicTimer = setTimeout(() => { 59 | this.runBALogic(2); 60 | }, 2 * config.lambda * 1000);*/ 61 | break; 62 | case 2: 63 | // end of status and start of propose 64 | if (this.leader === this.nodeID) { 65 | this.accepted.vi = uuid(); 66 | this.accepted.ki = 0; 67 | this.accepted.Ci = 'undefined'; 68 | if (this.status.length > 0) { 69 | const msg = this.status 70 | .groupBy(msg => msg.ki) 71 | .maxBy(arr => parseInt(arr[0]))[1][0]; 72 | if (msg.Ci !== 'undefined') { 73 | this.accepted.vi = msg.vi; 74 | this.accepted.ki = msg.ki; 75 | this.accepted.Ci = msg.Ci; 76 | } 77 | } 78 | const proposeMsg = { 79 | sender: this.nodeID, 80 | type: 'fl-propose', 81 | proposeMsg: { 82 | sender: this.nodeID, 83 | k: this.k, 84 | type: 'propose', 85 | vL: this.accepted.vi 86 | }, 87 | kL: this.accepted.ki, 88 | CL: this.accepted.Ci 89 | }; 90 | this.send(this.nodeID, 'broadcast', proposeMsg); 91 | this.proposeMsg = proposeMsg.proposeMsg; 92 | this.vLi = this.proposeMsg.vL; 93 | this.propose.push(this.proposeMsg); 94 | //this.send(this.nodeID, this.nodeID, proposeMsg); 95 | this.status = []; 96 | } 97 | this.registerTimeEvent( 98 | { name: 'runBALogic', params: { round: 3 } }, 99 | 2 * config.lambda * 1000 100 | ); 101 | /* 102 | this.BALogicTimer = setTimeout(() => { 103 | this.runBALogic(3); 104 | }, 2 * config.lambda * 1000);*/ 105 | break; 106 | case 3: 107 | // end of propose and start of commit 108 | if (this.vLi !== 'undefined') { 109 | // forward leader propose 110 | this.send(this.nodeID, 'broadcast', this.proposeMsg); 111 | const commitMsg = { 112 | sender: this.nodeID, 113 | k: this.k, 114 | type: 'commit', 115 | vLi: this.vLi 116 | }; 117 | this.send(this.nodeID, 'broadcast', commitMsg); 118 | this.commit.push(commitMsg); 119 | //this.send(this.nodeID, this.nodeID, commitMsg); 120 | } 121 | this.registerTimeEvent( 122 | { name: 'runBALogic', params: { round: 4 } }, 123 | 2 * config.lambda * 1000 124 | ); 125 | /* 126 | this.BALogicTimer = setTimeout(() => { 127 | this.runBALogic(4); 128 | }, 2 * config.lambda * 1000);*/ 129 | break; 130 | case 4: 131 | // end of commit and start of notify 132 | if (this.propose.some(msg => 133 | msg.k === this.k && msg.vL !== this.vLi)) { 134 | // leader has equivocated 135 | this.logger.info(['leader has equivocated, or vLi is undefined']); 136 | // do not commit 137 | } 138 | else { 139 | const C = this.commit.filter( 140 | msg => msg.vLi === this.vLi && msg.k === this.k); 141 | if (C.length >= this.nodeNum - this.f) { 142 | this.accepted.vi = this.vLi; 143 | this.accepted.Ci = C; 144 | const proof = 145 | JSON.parse(JSON.stringify(C)).splice(0, this.nodeNum - this.f); 146 | const notifyMsg = { 147 | sender: this.nodeID, 148 | type: 'notify', 149 | header: { 150 | sender: this.nodeID, 151 | type: 'notify-header', 152 | v: this.vLi 153 | }, 154 | Ci: proof 155 | }; 156 | this.send(this.nodeID, 'broadcast', notifyMsg); 157 | const k = notifyMsg.Ci[0].k; 158 | this.extendVector(this.notify, k); 159 | this.notify[k].push(notifyMsg); 160 | //this.send(this.nodeID, this.nodeID, notifyMsg); 161 | } 162 | } 163 | this.propose = []; 164 | this.commit = []; 165 | this.vLi = 'undefined'; 166 | this.registerTimeEvent( 167 | { name: 'runBALogic', params: { round: 1 } }, 168 | 2 * config.lambda * 1000 169 | ); 170 | /* 171 | this.BALogicTimer = setTimeout(() => { 172 | this.runBALogic(1); 173 | }, 2 * config.lambda * 1000);*/ 174 | break; 175 | default: 176 | this.logger.warning(['unknown round']); 177 | } 178 | 179 | } 180 | 181 | onMsgEvent(msgEvent) { 182 | super.onMsgEvent(msgEvent); 183 | const msg = msgEvent.packet.content; 184 | this.logger.info(['recv', this.logger.round(msgEvent.triggeredTime), JSON.stringify(msg)]); 185 | if (this.isDecided) { 186 | return; 187 | } 188 | switch(msg.type) { 189 | case 'status': 190 | if (this.leader === this.nodeID && msg.k === this.k) { 191 | // verify msg.Ci 192 | this.status.push(msg); 193 | } 194 | break; 195 | case 'fl-propose': 196 | if (msg.sender === this.leader) { 197 | if (msg.kL >= this.accepted.ki) { 198 | this.proposeMsg = msg.proposeMsg; 199 | this.vLi = this.proposeMsg.vL; 200 | } 201 | else { 202 | // leader is faulty 203 | this.vLi = 'undefined'; 204 | } 205 | } 206 | break; 207 | case 'propose': 208 | if (msg.k !== this.k) return; 209 | this.propose.push(msg); 210 | break; 211 | case 'commit': 212 | if (msg.k !== this.k) return; 213 | this.commit.push(msg); 214 | break; 215 | case 'notify': 216 | // sanity check on msg.Ci 217 | const k = msg.Ci[0].k; 218 | this.extendVector(this.notify, k); 219 | this.notify[k].push(msg); 220 | if (this.notify[k].length >= this.f + 1) { 221 | const headers = this.notify[k] 222 | .map(notifyMsg => notifyMsg.header); 223 | const headerMsg = { 224 | sender: this.nodeID, 225 | type: 'notify-headers', 226 | headers: headers 227 | }; 228 | this.send(this.nodeID, 'broadcast', headerMsg); 229 | this.decide(headers[0].v); 230 | } 231 | break; 232 | case 'notify-headers': 233 | // sanity check 234 | const headerMsg = { 235 | sender: this.nodeID, 236 | type: 'notify-headers', 237 | headers: msg.headers 238 | }; 239 | this.send(this.nodeID, 'broadcast', headerMsg); 240 | this.decide(msg.headers[0].v); 241 | break; 242 | default: 243 | this.logger.warning(['unknown message type']); 244 | } 245 | } 246 | 247 | onTimeEvent(timeEvent) { 248 | super.onTimeEvent(timeEvent); 249 | if (this.isDecided) { 250 | return; 251 | } 252 | const functionMeta = timeEvent.functionMeta; 253 | switch (functionMeta.name) { 254 | case 'start': 255 | const initStatusMsg = { 256 | sender: this.nodeID, 257 | type: 'status', 258 | k: this.k, 259 | vi: this.accepted.vi, 260 | ki: this.accepted.ki, 261 | Ci: this.accepted.Ci 262 | }; 263 | if (this.nodeID === this.leader) { 264 | this.status.push(initStatusMsg); 265 | } 266 | else { 267 | this.send(this.nodeID, this.leader, initStatusMsg); 268 | } 269 | this.registerTimeEvent( 270 | { name: 'runBALogic', params: { round: 2 } }, 271 | 2 * config.lambda * 1000 272 | ); 273 | break; 274 | case 'runBALogic': 275 | this.runBALogic(functionMeta.params.round); 276 | break; 277 | } 278 | } 279 | 280 | constructor(nodeID, nodeNum, network, registerTimeEvent) { 281 | super(nodeID, nodeNum, network, registerTimeEvent); 282 | //this.isCooling = false; 283 | this.f = (this.nodeNum % 2 === 0) ? 284 | this.nodeNum / 2 - 1 : (this.nodeNum - 1) / 2; 285 | 286 | // BA related 287 | // store all accepted 288 | this.accepteds = []; 289 | this.accepted = { 290 | vi: 'undefined', 291 | ki: 0, 292 | Ci: 'undefined' 293 | }; 294 | this.k = 1; 295 | this.vLi = 'undefined'; 296 | this.leader = '' + (this.k % this.nodeNum + 1); 297 | this.status = []; 298 | this.propose = []; 299 | this.commit = []; 300 | this.notify = []; 301 | this.isDecided = false; 302 | this.decidedValue = undefined; 303 | 304 | this.registerTimeEvent({ name: 'start', params: {} }, 0); 305 | /* 306 | const targetStartTime = process.argv[4]; 307 | setTimeout(() => { 308 | this.send(this.nodeID, this.leader, initStatusMsg); 309 | // go to round 2 after 2l 310 | setTimeout(() => { 311 | this.runBALogic(2); 312 | }, 2 * config.lambda * 1000); 313 | }, targetStartTime - Date.now());*/ 314 | } 315 | } 316 | //const n = new VMwareNode(process.argv[2], process.argv[3]); 317 | module.exports = VMwareNode; -------------------------------------------------------------------------------- /ba-algo/algorand.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('./node'); 4 | const config = require('../config'); 5 | const uuid = require('uuid/v4'); 6 | 7 | class AlgorandNode extends Node { 8 | 9 | extendVectors(v, until) { 10 | const n = until - v.length + 1 11 | for (let i = 0; i < n; i++) { 12 | v.push([]); 13 | } 14 | } 15 | 16 | getMaxResult(vector) { 17 | if (vector === undefined || vector.length === 0) { 18 | return { value: undefined, count: 0 }; 19 | } 20 | return vector.groupBy(msg => msg.v) 21 | // [[value, [msg]], [value, [msg]]] 22 | .map(e => ({ value: e[0], count: e[1].length })) 23 | // [{ value: v, count: 1 }, { value: v, count: 2 }] 24 | .maxBy(e => e.count); 25 | // { value: v, count: max } 26 | } 27 | 28 | // since one node can next vote on multiple values 29 | // we can not use getMaxResult() 30 | // next vote should only contains more than 2t + 1 of any value 31 | // since it will skip to the next period immediately when it contains 2t + 1 32 | // of any value 33 | getMaxNextVoteResult(p) { 34 | if (this.nextVotes[p] === undefined || this.nextVotes[p].length === 0) { 35 | return { value: undefined, count: 0 }; 36 | } 37 | const m = {}; 38 | this.nextVotes[p].forEach(nextVote => { 39 | if (m[nextVote.v] === undefined) { 40 | m[nextVote.v] = [nextVote]; 41 | } 42 | else { 43 | m[nextVote.v].push(nextVote); 44 | } 45 | }); 46 | let maxCount = 0, value = undefined; 47 | for (let v in m) { 48 | m[v] = m[v].unique(nextVote => nextVote.sender); 49 | if (m[v].length > maxCount) { 50 | maxCount = m[v].length; 51 | value = v; 52 | } 53 | } 54 | return { value: value, count: maxCount}; 55 | } 56 | 57 | decide(p) { 58 | let result = this.getMaxResult(this.certVotes[p]); 59 | if (result.count >= 2 * this.f + 1) { 60 | this.logger.info([`decides on ${result.value} in period ${this.p}`]); 61 | const proof = this.certVotes[p] 62 | .filter(certVote => certVote.v === result.value) 63 | .splice(0, 2 * this.f + 1); 64 | this.send(this.nodeID, 'broadcast', { 65 | type: 'certificate', 66 | v: result.value, 67 | p: p, 68 | proof: proof 69 | }); 70 | this.decidedValue = result.value; 71 | this.isDecided = true; 72 | } 73 | } 74 | 75 | forwardPeriod(p) { 76 | if (p < this.p) return; 77 | const result = this.getMaxNextVoteResult(p); 78 | if (result.count >= 2 * this.f + 1) { 79 | this.p = p + 1; 80 | // dynamic lambda 81 | //this.lambda = config.lambda * Math.pow(2, this.iter - 1); 82 | this.step = 1; 83 | this.stV = result.value; 84 | this.runBALogic(); 85 | } 86 | } 87 | 88 | getConditions() { 89 | if (this.p < 2) return { isBot: false, isValue: false, value: undefined }; 90 | const result = this.getMaxNextVoteResult(this.p - 1); 91 | const isValue = (result.value !== 'BOT' && result.count >= 2 * this.f + 1); 92 | return { 93 | isBot: (result.value === 'BOT' && result.count >= 2 * this.f + 1), 94 | isValue: isValue, 95 | value: (isValue) ? result.value : undefined 96 | }; 97 | } 98 | 99 | runBALogic() { 100 | switch (this.step) { 101 | case 1: { 102 | const conditions = this.getConditions(); 103 | const proposeMsg = { 104 | type: 'propose', 105 | p: this.p, 106 | randomness: Math.floor(Math.random() * 1000000000 + 1), 107 | sender: this.nodeID 108 | }; 109 | if (this.p === 1 || (this.p >= 2 && conditions.isBot)) { 110 | // i proposes vi, which he propagates together with his period p credential 111 | proposeMsg.v = this.v; 112 | } 113 | else if (this.p >= 2 && conditions.isValue) { 114 | // i proposes v, which he propagates together with his period p credential 115 | proposeMsg.v = conditions.value; 116 | } 117 | this.send(this.nodeID, 'broadcast', proposeMsg); 118 | this.extendVectors(this.proposes, this.p); 119 | this.proposes[this.p].push(proposeMsg); 120 | this.registerTimeEvent({ 121 | name: 'runBALogic', 122 | params: { p: this.p, step: 2 } 123 | }, 2 * config.lambda * 1000); 124 | break; 125 | } 126 | case 2: { 127 | const conditions = this.getConditions(); 128 | const softVote = { type: 'soft', p: this.p, sender: this.nodeID }; 129 | if (this.p === 1 || this.p >= 2 && conditions.isBot) { 130 | // i identifies his leader li,p for period p and soft-votes the value v proposed by li,p 131 | softVote.v = this.proposes[this.p] 132 | .minBy(proposeMsg => proposeMsg.randomness).v; 133 | } 134 | else if (this.p >= 2 && conditions.isValue) { 135 | // i soft-votes v 136 | softVote.v = conditions.value; 137 | } 138 | this.send(this.nodeID, 'broadcast', softVote); 139 | this.extendVectors(this.softVotes, this.p); 140 | this.softVotes[this.p].push(softVote); 141 | // directly enter step 3 142 | this.step = 3; 143 | this.hasCertified.length = this.p + 1; 144 | this.hasCertified[this.p] = undefined; 145 | // directly perform step 3 condition check 146 | if (this.hasCertified[this.p] === undefined && 147 | this.step === 3) { 148 | const result = this.getMaxResult(this.softVotes[this.p]); 149 | if (result.value !== 'BOT' && result.count >= 2 * this.f + 1) { 150 | const certVote = { 151 | type: 'cert', 152 | p: this.p, 153 | v: result.value, 154 | sender: this.nodeID 155 | }; 156 | this.hasCertified[this.p] = result.value; 157 | this.send(this.nodeID, 'broadcast', certVote); 158 | this.extendVectors(this.certVotes, this.p); 159 | this.certVotes[this.p].push(certVote); 160 | } 161 | } 162 | this.registerTimeEvent({ 163 | name: 'runBALogic', 164 | params: { p: this.p, step: 4 } 165 | }, 2 * config.lambda * 1000); 166 | break; 167 | } 168 | case 3: { 169 | // step 3 is message driven 170 | break; 171 | } 172 | case 4: { 173 | const nextVote = { type: 'next', p: this.p, sender: this.nodeID }; 174 | const conditions = this.getConditions(); 175 | if (this.hasCertified[this.p] !== undefined) { 176 | // next vote v 177 | nextVote.v = this.hasCertified[this.p]; 178 | } 179 | else if (this.p >= 2 && conditions.isBot) { 180 | nextVote.v = 'BOT'; 181 | } 182 | else { 183 | nextVote.v = this.stV; 184 | } 185 | this.send(this.nodeID, 'broadcast', nextVote); 186 | this.extendVectors(this.nextVotes, this.p); 187 | this.nextVotes[this.p].push(nextVote); 188 | // directly enter step 5 189 | this.step = 5; 190 | // directly perform step 5 condition check 191 | this.hasNextVoteBySoftVote.length = this.p + 1; 192 | this.hasNextVoteBySoftVote[this.p] = false; 193 | this.hasNextVoteByNextVote.length = this.p + 1; 194 | this.hasNextVoteByNextVote[this.p] = false; 195 | const result = this.getMaxResult(this.softVotes[this.p]); 196 | if (result.value !== 'BOT' && result.count >= 2 * this.f + 1) { 197 | const nextVote = { 198 | type: 'next', 199 | p: this.p, 200 | v: result.value, 201 | sender: this.nodeID 202 | }; 203 | this.send(this.nodeID, 'broadcast', nextVote); 204 | this.extendVectors(this.nextVotes, this.p); 205 | this.nextVotes[this.p].push(nextVote); 206 | this.hasNextVoteBySoftVote[this.p] = true; 207 | } 208 | const condition = this.getConditions(); 209 | if (this.p >= 2 && condition.isBot && 210 | this.hasCertified[this.p] === undefined) { 211 | const nextVote = { 212 | type: 'next', 213 | p: this.p, 214 | v: 'BOT', 215 | sender: this.nodeID 216 | }; 217 | this.send(this.nodeID, 'broadcast', nextVote); 218 | this.extendVectors(this.nextVotes, this.p); 219 | this.nextVotes[this.p].push(nextVote); 220 | this.hasNextVoteByNextVote[this.p] = true; 221 | } 222 | break; 223 | } 224 | case 5: { 225 | // step 5 is message driven 226 | // TODO: directly check once 227 | break; 228 | } 229 | } 230 | } 231 | 232 | onMsgEvent(msgEvent) { 233 | super.onMsgEvent(msgEvent); 234 | const msg = msgEvent.packet.content; 235 | this.logger.info(['recv', this.logger.round(msgEvent.triggeredTime), this.step, JSON.stringify(msg)]); 236 | if (this.isDecided) { 237 | return; 238 | } 239 | switch (msg.type) { 240 | case 'propose': { 241 | this.extendVectors(this.proposes, msg.p); 242 | this.proposes[msg.p].push(msg); 243 | break; 244 | } 245 | case 'soft': { 246 | this.extendVectors(this.softVotes, msg.p); 247 | this.softVotes[msg.p].push(msg); 248 | // If i sees 2t + 1 soft-votes for some value v != ⊥, then i cert-votes v 249 | // required msg.p === this.p? 250 | if (this.hasCertified[this.p] === undefined && 251 | this.step === 3 && 252 | this.p === msg.p) { 253 | const result = this.getMaxResult(this.softVotes[msg.p]); 254 | if (result.value !== 'BOT' && result.count >= 2 * this.f + 1) { 255 | const certVote = { 256 | type: 'cert', 257 | p: this.p, 258 | v: result.value, 259 | sender: this.nodeID 260 | }; 261 | this.hasCertified[this.p] = result.value; 262 | this.send(this.nodeID, 'broadcast', certVote); 263 | this.extendVectors(this.certVotes, this.p); 264 | this.certVotes[this.p].push(certVote); 265 | } 266 | } 267 | else if (!this.hasNextVoteBySoftVote[this.p] && 268 | this.step === 5 && this.p === msg.p) { 269 | const result = this.getMaxResult(this.softVotes[msg.p]); 270 | if (result.value !== 'BOT' && result.count >= 2 * this.f + 1) { 271 | const nextVote = { 272 | type: 'next', 273 | p: this.p, 274 | v: result.value, 275 | sender: this.nodeID 276 | }; 277 | this.send(this.nodeID, 'broadcast', nextVote); 278 | this.extendVectors(this.nextVotes, this.p); 279 | this.nextVotes[this.p].push(nextVote); 280 | this.hasNextVoteBySoftVote[this.p] = true; 281 | } 282 | } 283 | break; 284 | } 285 | case 'cert': { 286 | this.extendVectors(this.certVotes, msg.p); 287 | this.certVotes[msg.p].push(msg); 288 | this.decide(msg.p); 289 | break; 290 | } 291 | case 'next': { 292 | this.extendVectors(this.nextVotes, msg.p); 293 | this.nextVotes[msg.p].push(msg); 294 | const condition = this.getConditions(); 295 | if (!this.hasNextVoteByNextVote[this.p] && 296 | this.step === 5 && 297 | this.p >= 2 && condition.isBot && 298 | this.hasCertified[this.p] === undefined) { 299 | const nextVote = { 300 | type: 'next', 301 | p: this.p, 302 | v: 'BOT', 303 | sender: this.nodeID 304 | }; 305 | this.send(this.nodeID, 'broadcast', nextVote); 306 | this.extendVectors(this.nextVotes, this.p); 307 | this.nextVotes[this.p].push(nextVote); 308 | this.hasNextVoteByNextVote[this.p] = true; 309 | } 310 | this.forwardPeriod(msg.p); 311 | break; 312 | } 313 | case 'certificate': { 314 | msg.proof.forEach(certVote => { 315 | if (!this.certVotes[msg.p] 316 | .some(myCertVote => myCertVote.sender === certVote.sender)) { 317 | this.certVotes[msg.p].push(certVote); 318 | } 319 | }); 320 | this.decide(msg.p); 321 | break; 322 | } 323 | default: 324 | console.log('unknown message type:', msg); 325 | } 326 | } 327 | 328 | onTimeEvent(timeEvent) { 329 | super.onTimeEvent(timeEvent); 330 | const functionMeta = timeEvent.functionMeta; 331 | // prevent older events 332 | if (functionMeta.params.p < this.p) return; 333 | this.step = functionMeta.params.step; 334 | this.runBALogic(); 335 | } 336 | 337 | constructor(nodeID, nodeNum, network, registerTimeEvent) { 338 | super(nodeID, nodeNum, network, registerTimeEvent); 339 | this.f = (this.nodeNum % 3 === 0) ? 340 | this.nodeNum / 3 - 1 : Math.floor(this.nodeNum / 3); 341 | // BA related 342 | this.proposes = []; 343 | this.certVotes = []; 344 | this.softVotes = []; 345 | this.nextVotes = []; 346 | this.hasCertified = [ undefined, undefined ]; 347 | this.hasNextVoteBySoftVote = [ false, false ]; 348 | this.hasNextVoteByNextVote = [ false, false ]; 349 | 350 | this.p = 1; 351 | this.v = uuid(); 352 | this.stV = 'BOT'; 353 | 354 | this.isDecided = false; 355 | this.lambda = config.lambda; 356 | this.registerTimeEvent({ name: 'runBALogic', params: { p: this.p, step: 1 } }, 0); 357 | } 358 | } 359 | //const n = new DEXONNode(process.argv[2], process.argv[3]); 360 | module.exports = AlgorandNode; 361 | -------------------------------------------------------------------------------- /ba-algo/vmware-ba/adaptive.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('../node'); 4 | const config = require('../../config'); 5 | const uuid = require('uuid/v4'); 6 | 7 | class VMwareNode extends Node { 8 | 9 | // extend vector v to be able to access v[n] = array 10 | extendVector(v, n) { 11 | if (v[n] === undefined) { 12 | v[n] = []; 13 | } 14 | } 15 | 16 | decide(v) { 17 | //clearTimeout(this.BALogicTimer); 18 | this.logger.info([`decide on ${v}`]); 19 | this.isDecided = true; 20 | this.decidedValue = v; 21 | } 22 | 23 | runBALogic(round) { 24 | switch (round) { 25 | case 1: 26 | // end of notify and start of status 27 | this.extendVector(this.notify, this.k); 28 | if (this.notify[this.k].length > 0) { 29 | const msg = this.notify[this.k][0]; 30 | this.accepted.vi = msg.header.v; 31 | this.accepted.Ci = msg.Ci; 32 | this.accepted.ki = this.k; 33 | }; 34 | this.k++; 35 | const initStatusMsg = { 36 | sender: this.nodeID, 37 | type: 'status', 38 | k: this.k, 39 | vi: this.accepted.vi, 40 | ki: this.accepted.ki, 41 | Ci: this.accepted.Ci 42 | }; 43 | this.status.push(initStatusMsg); 44 | this.send(this.nodeID, 'broadcast', initStatusMsg); 45 | this.registerTimeEvent( 46 | { name: 'runBALogic', params: { round: 2 } }, 47 | 2 * config.lambda * 1000 48 | ); 49 | /* 50 | this.BALogicTimer = setTimeout(() => { 51 | this.runBALogic(2); 52 | }, 2 * config.lambda * 1000);*/ 53 | break; 54 | case 2: 55 | // end of status and start of prepare1 56 | this.accepted.vi = uuid(); 57 | this.accepted.ki = 0; 58 | this.accepted.Ci = 'undefined'; 59 | if (this.status.length > 0) { 60 | const msg = this.status 61 | .groupBy(msg => msg.ki) 62 | // [['ki', [status msg]], ['ki', [status msg]]] 63 | .maxBy(arr => parseInt(arr[0]))[1][0]; 64 | if (msg.Ci !== 'undefined') { 65 | this.accepted.vi = msg.vi; 66 | this.accepted.ki = msg.ki; 67 | this.accepted.Ci = msg.Ci; 68 | } 69 | } 70 | const prepare1Msg = { 71 | sender: this.nodeID, 72 | type: 'prepare1', 73 | vi: this.accepted.vi, 74 | k: this.k 75 | }; 76 | this.send(this.nodeID, 'broadcast', prepare1Msg); 77 | this.prepare1.push(prepare1Msg); 78 | //this.send(this.nodeID, this.nodeID, prepare1Msg); 79 | this.status = []; 80 | this.registerTimeEvent( 81 | { name: 'runBALogic', params: { round: 3 } }, 82 | 2 * config.lambda * 1000 83 | ); 84 | /* 85 | this.BALogicTimer = setTimeout(() => { 86 | this.runBALogic(3); 87 | }, 2 * config.lambda * 1000);*/ 88 | break; 89 | case 3: 90 | // end of prepare1 and start of prepare2 91 | this.prepare1.forEach(msg => { 92 | const prepare2Msg = { 93 | sender: this.nodeID, 94 | type: 'prepare2', 95 | vi: msg.vi, 96 | k: msg.k 97 | }; 98 | if (msg.sender === this.nodeID) { 99 | this.prepare2.push(prepare2Msg); 100 | } 101 | else { 102 | this.send(this.nodeID, msg.sender, prepare2Msg); 103 | } 104 | }); 105 | this.prepare1 = []; 106 | this.registerTimeEvent( 107 | { name: 'runBALogic', params: { round: 4 } }, 108 | 2 * config.lambda * 1000 109 | ); 110 | /* 111 | this.BALogicTimer = setTimeout(() => { 112 | this.runBALogic(4); 113 | }, 2 * config.lambda * 1000);*/ 114 | break; 115 | case 4: 116 | // end of prepare2 and start of propose 117 | if (this.prepare2.length >= this.nodeNum - this.f) { 118 | const proposeMsg = { 119 | sender: this.nodeID, 120 | type: 'fl-propose', 121 | proposeMsg: { 122 | sender: this.nodeID, 123 | k: this.k, 124 | type: 'propose', 125 | vL: this.accepted.vi, 126 | prepared: this.prepare2.splice(0, this.nodeNum - this.f) 127 | }, 128 | kL: this.accepted.ki, 129 | CL: this.accepted.Ci 130 | }; 131 | this.send(this.nodeID, 'broadcast', proposeMsg); 132 | this.flPropose.push(proposeMsg); 133 | //this.send(this.nodeID, this.nodeID, proposeMsg); 134 | } 135 | this.prepare2 = []; 136 | this.registerTimeEvent( 137 | { name: 'runBALogic', params: { round: 5 } }, 138 | 2 * config.lambda * 1000 139 | ); 140 | /* 141 | this.BALogicTimer = setTimeout(() => { 142 | this.runBALogic(5); 143 | }, 2 * config.lambda * 1000);*/ 144 | break; 145 | case 5: 146 | // end of propose and start of elect 147 | const electMsg = { 148 | sender: this.nodeID, 149 | type: 'elect', 150 | // VRF 151 | y: Math.floor(Math.random() * 1000000000 + 1) 152 | }; 153 | this.send(this.nodeID, 'broadcast', electMsg); 154 | this.elect[this.nodeID] = electMsg.y; 155 | //this.send(this.nodeID, this.nodeID, electMsg); 156 | this.registerTimeEvent( 157 | { name: 'runBALogic', params: { round: 6 } }, 158 | 2 * config.lambda * 1000 159 | ); 160 | /* 161 | this.BALogicTimer = setTimeout(() => { 162 | this.runBALogic(6); 163 | }, 2 * config.lambda * 1000);*/ 164 | break; 165 | case 6: 166 | // end of elect and start of commit 167 | // remove duplicate leader proposal 168 | this.flPropose = this.flPropose 169 | .groupBy(msg => msg.sender) 170 | // [[sender, [msg]], [sender, [msg]]] 171 | .filter(arr => arr[1].length <= 1) 172 | .map(arr => arr[1]) 173 | // [[msg], [msg]] 174 | .flat(); 175 | this.flPropose.sort((msgA, msgB) => { 176 | if (msgA.kL < msgB.kL) { 177 | return 1; 178 | } 179 | else if (msgA.kL > msgB.kL) { 180 | return -1; 181 | } 182 | else { 183 | return (this.elect[msgA.sender] < this.elect[msgB.sender]) ? 184 | 1 : -1; 185 | } 186 | }); 187 | const bestProposal = this.flPropose[0]; 188 | if (bestProposal === undefined || bestProposal.kL < this.accepted.ki) { 189 | // leader is faulty or no leader 190 | this.vLi = 'undefined'; 191 | } 192 | else { 193 | this.proposeMsg = bestProposal.proposeMsg; 194 | this.vLi = this.proposeMsg.vL; 195 | } 196 | if (this.vLi !== 'undefined') { 197 | // forward leader propose 198 | this.send(this.nodeID, 'broadcast', this.proposeMsg); 199 | const commitMsg = { 200 | sender: this.nodeID, 201 | k: this.k, 202 | type: 'commit', 203 | vLi: this.vLi, 204 | y: this.elect[this.proposeMsg.sender] 205 | }; 206 | this.send(this.nodeID, 'broadcast', commitMsg); 207 | this.commit.push(commitMsg); 208 | //this.send(this.nodeID, this.nodeID, commitMsg); 209 | } 210 | this.flPropose = []; 211 | this.elect = {}; 212 | this.registerTimeEvent( 213 | { name: 'runBALogic', params: { round: 7 } }, 214 | 2 * config.lambda * 1000 215 | ); 216 | /* 217 | this.BALogicTimer = setTimeout(() => { 218 | this.runBALogic(7); 219 | }, 2 * config.lambda * 1000);*/ 220 | break; 221 | case 7: 222 | // end of commit and start of notify 223 | if (this.propose.some(msg => 224 | msg.k === this.k && msg.vL !== this.vLi)) { 225 | // leader has equivocated 226 | // do not commit 227 | this.logger.warning(['leader has equivocated']); 228 | } 229 | else { 230 | const C = this.commit.filter( 231 | msg => msg.vLi === this.vLi && msg.k === this.k); 232 | if (C.length >= this.nodeNum - this.f) { 233 | this.accepted.vi = this.vLi; 234 | this.accepted.Ci = C; 235 | const proof = 236 | JSON.parse(JSON.stringify(C)).splice(0, this.nodeNum - this.f); 237 | const notifyMsg = { 238 | sender: this.nodeID, 239 | type: 'notify', 240 | header: { 241 | sender: this.nodeID, 242 | type: 'notify-header', 243 | v: this.vLi 244 | }, 245 | Ci: proof 246 | }; 247 | this.send(this.nodeID, 'broadcast', notifyMsg); 248 | const k = notifyMsg.Ci[0].k; 249 | this.extendVector(this.notify, k); 250 | this.notify[k].push(notifyMsg); 251 | //this.send(this.nodeID, this.nodeID, notifyMsg); 252 | } 253 | } 254 | this.propose = []; 255 | this.commit = []; 256 | this.vLi = 'undefined'; 257 | this.registerTimeEvent( 258 | { name: 'runBALogic', params: { round: 1 } }, 259 | 2 * config.lambda * 1000 260 | ); 261 | /* 262 | this.BALogicTimer = setTimeout(() => { 263 | this.runBALogic(1); 264 | }, 2 * config.lambda * 1000);*/ 265 | break; 266 | default: 267 | this.logger.warning(['unknown round']); 268 | } 269 | 270 | } 271 | 272 | onMsgEvent(msgEvent) { 273 | super.onMsgEvent(msgEvent); 274 | const msg = msgEvent.packet.content; 275 | this.logger.info(['recv', this.logger.round(msgEvent.triggeredTime), JSON.stringify(msg)]); 276 | if (this.isDecided) { 277 | return; 278 | } 279 | switch(msg.type) { 280 | case 'status': 281 | // verify msg.Ci 282 | this.status.push(msg); 283 | break; 284 | case 'prepare1': 285 | this.prepare1.push(msg); 286 | break; 287 | case 'prepare2': 288 | this.prepare2.push(msg); 289 | break; 290 | case 'fl-propose': 291 | if (msg.proposeMsg.prepared.length >= this.nodeNum - this.f) 292 | this.flPropose.push(msg); 293 | break; 294 | case 'propose': 295 | this.propose.push(msg); 296 | break; 297 | case 'elect': 298 | this.elect[msg.sender] = msg.y; 299 | break; 300 | case 'commit': 301 | this.commit.push(msg); 302 | break; 303 | case 'notify': 304 | const k = msg.Ci[0].k; 305 | this.extendVector(this.notify, k); 306 | this.notify[k].push(msg); 307 | if (this.notify[k].length >= this.f + 1) { 308 | const headers = this.notify[k] 309 | .map(notifyMsg => notifyMsg.header); 310 | const headerMsg = { 311 | sender: this.nodeID, 312 | type: 'notify-headers', 313 | headers: headers 314 | }; 315 | this.send(this.nodeID, 'broadcast', headerMsg); 316 | this.decide(headers[0].v); 317 | } 318 | break; 319 | case 'notify-headers': 320 | // sanity check 321 | const headerMsg = { 322 | sender: this.nodeID, 323 | type: 'notify-headers', 324 | headers: msg.headers 325 | }; 326 | this.send(this.nodeID, 'broadcast', headerMsg); 327 | this.decide(msg.headers[0].v); 328 | break; 329 | default: 330 | this.logger.warning(['unknown message type']); 331 | } 332 | } 333 | 334 | onTimeEvent(timeEvent) { 335 | super.onTimeEvent(timeEvent); 336 | if (this.isDecided) { 337 | return; 338 | } 339 | const functionMeta = timeEvent.functionMeta; 340 | switch (functionMeta.name) { 341 | case 'start': 342 | const initStatusMsg = { 343 | sender: this.nodeID, 344 | type: 'status', 345 | k: this.k, 346 | vi: this.accepted.vi, 347 | ki: this.accepted.ki, 348 | Ci: this.accepted.Ci 349 | }; 350 | this.status.push(initStatusMsg); 351 | this.send(this.nodeID, 'broadcast', initStatusMsg); 352 | this.registerTimeEvent( 353 | { name: 'runBALogic', params: { round: 2 } }, 354 | 2 * config.lambda * 1000 355 | ); 356 | break; 357 | case 'runBALogic': 358 | this.runBALogic(functionMeta.params.round); 359 | break; 360 | } 361 | } 362 | 363 | constructor(nodeID, nodeNum, network, registerTimeEvent) { 364 | super(nodeID, nodeNum, network, registerTimeEvent); 365 | //this.isCooling = false; 366 | this.f = (this.nodeNum % 2 === 0) ? 367 | this.nodeNum / 2 - 1 : (this.nodeNum - 1) / 2; 368 | 369 | // BA related 370 | // store all accepted 371 | this.accepteds = []; 372 | this.accepted = { 373 | vi: 'undefined', 374 | ki: 0, 375 | Ci: 'undefined' 376 | }; 377 | this.k = 1; 378 | this.vLi = 'undefined'; 379 | this.leader; 380 | this.status = []; 381 | this.flPropose = []; 382 | this.propose = []; 383 | this.commit = []; 384 | this.notify = []; 385 | this.prepare1 = []; 386 | this.prepare2 = []; 387 | this.elect = {}; 388 | this.isDecided = false; 389 | this.decidedValue = undefined; 390 | 391 | this.registerTimeEvent({ name: 'start', params: {} }, 0); 392 | 393 | /* 394 | const targetStartTime = process.argv[4]; 395 | setTimeout(() => { 396 | this.send(this.nodeID, 'broadcast', initStatusMsg); 397 | // go to round 2 after 2l 398 | setTimeout(() => { 399 | this.runBALogic(2); 400 | }, 2 * config.lambda * 1000); 401 | }, targetStartTime - Date.now());*/ 402 | } 403 | } 404 | //const n = new VMwareNode(process.argv[2], process.argv[3]); 405 | module.exports = VMwareNode; -------------------------------------------------------------------------------- /ba-algo/libraBFT.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('./node'); 4 | const uuid = require('uuid/v4'); 5 | let config = require('../config'); 6 | 7 | const HotStuffMsgTypeNextView = 'hot-stuff-next-view'; 8 | const HotStuffEventNextViewInterrupt = 'hot-stuff-next-view-interrupt'; 9 | const HotStuffMsgTypeUpdate = 'hot-stuff-update'; 10 | const TimeOutMSG = 'pacemaker-timeout-msg'; 11 | 12 | const HotStuffGenesisQC = { 13 | view: -1, 14 | request: 'hot-stuff-genesis-null-QC', 15 | } 16 | 17 | const HotStuffGenesisBlock = { 18 | view: -1, 19 | request: 'hot-stuff-genesis-block', 20 | QC: HotStuffGenesisQC, 21 | }; 22 | 23 | 24 | function extendVector(v, n) { 25 | if (v[n] === undefined) { 26 | v[n] = []; 27 | } 28 | } 29 | 30 | function getPrimaryByView(view, nodeNum) { 31 | return ((view + nodeNum) % nodeNum + 1).toString(); 32 | } 33 | 34 | class HotStuffTMNode extends Node { 35 | 36 | getBlockVotesNum(msg) { 37 | const votesNum = this.blockVotes[msg.view]. 38 | filter(m => m.request === msg.request). 39 | groupBy(m => m.sourceReplica).length; 40 | return votesNum; 41 | } 42 | 43 | getBlockRequest(n) { 44 | if (n == 0) { 45 | return HotStuffGenesisQC; 46 | } 47 | if (n < 0) { 48 | console.log(`error when querying block: ${n}`); 49 | return undefined; 50 | } 51 | if (this.localBlocks === undefined) { 52 | console.log(`error when querying block: ${n}`); 53 | return undefined; 54 | } 55 | return this.localBlocks[n].request; 56 | } 57 | 58 | // since leaders generate a new request from uuid(), we used it as block identifier (blockhash) 59 | getBlockByRequest(request) { 60 | if (this.localBlocksMap === undefined) { 61 | this.localBlocksMap = {}; 62 | } 63 | return this.localBlocksMap[request]; 64 | } 65 | 66 | insertBlockByRequest(block) { 67 | if (this.localBlocksMap === undefined) { 68 | this.localBlocksMap = {}; 69 | } 70 | if (block.dummyBlocks !== undefined) { 71 | if (block.dummyBlocks.length > 0) { 72 | block.dummyBlocks.forEach(dummyBlock => { 73 | this.logger.info(['insert dummy', JSON.stringify(dummyBlock)]); 74 | this.insertBlockByRequest(dummyBlock); 75 | }); 76 | } 77 | // delete block.dummyBlocks; 78 | } 79 | 80 | this.logger.info(['inserting-block', JSON.stringify(block)]) 81 | this.localBlocksMap[block.request] = block; 82 | if (this.localBlocksRequestMap[block.view] === undefined) { 83 | this.localBlocksRequestMap[block.view] = [] 84 | } 85 | this.localBlocksRequestMap[block.view].push(block.request); 86 | } 87 | 88 | generateTMQC(view) { 89 | if (this.nextView[view] === undefined) { 90 | console.log('error'); 91 | } 92 | let signers = this.block = this.nextView[view].map(m => { 93 | return m.sourceReplica 94 | }) 95 | if (signers.length < this.nodeNum - this.f) { 96 | console.log("generated QC with insufficient signatures"); 97 | process.exit(0); 98 | } 99 | const TMQC = { 100 | request: PaceMakerTimeOutQC, 101 | signers: signers, 102 | view: view, 103 | } 104 | } 105 | 106 | generateQC(msg) { 107 | // work as a threshold signautre 108 | let signers = this.blockVotes[msg.view] 109 | .filter(m => m.request === msg.request) 110 | .map(m => { 111 | return m.sourceReplica 112 | }) 113 | if (signers.length < this.nodeNum - this.f) { 114 | console.log("generated QC with insufficient signatures"); 115 | process.exit(0); 116 | } 117 | const QC = { 118 | request: msg.request, 119 | view: msg.view, 120 | signers: signers, 121 | }; 122 | return QC; 123 | } 124 | 125 | 126 | // paceMaker 127 | updateQCHigh(QC) { 128 | if (this.highQC === HotStuffGenesisQC || QC.view > this.highQC.view) { 129 | this.registerNewNextViewInterrupt(); 130 | this.highQC = QC; 131 | } 132 | } 133 | 134 | updateLockQC(QC) { 135 | if (this.lockedQC === HotStuffGenesisQC || QC.view > this.lockedQC.view) { 136 | this.lockedQC = QC; 137 | this.logger.info(['locked-QC', JSON.stringify(QC)]); 138 | } 139 | } 140 | 141 | isBroadcast(view) { 142 | 143 | if (this.isBroadcastMap[view] !== undefined) { 144 | return true; 145 | } 146 | return false; 147 | } 148 | 149 | setBroadcast(view) { 150 | 151 | this.isBroadcastMap[view] = true; 152 | } 153 | 154 | receiveVote(msg) { 155 | if(msg.view < this.lastVotedView) { 156 | return; 157 | } 158 | extendVector(this.blockVotes, msg.view); 159 | if (this.blockVotes[msg.view].filter(m => m.sourceReplica === msg.sourceReplica).length === 0) { 160 | this.blockVotes[msg.view].push(msg); 161 | } 162 | if (this.getBlockVotesNum(msg) >= this.nodeNum - this.f) { 163 | if (!this.isBroadcast(msg.view)) { 164 | this.logger.info(['enough vote', JSON.stringify(msg)]); 165 | const QC = this.generateQC(msg); 166 | this.updateQCHigh(QC); 167 | this.setBroadcast(msg.view); 168 | this.proposeNextRequest(msg.view); 169 | } 170 | } 171 | } 172 | 173 | getBlockRequestByView(view) { 174 | if (this.localBlocksRequestMap === undefined) { 175 | this.localBlocksRequestMap = {}; 176 | } 177 | if (this.localBlocksRequestMap[view] !== undefined) { 178 | return this.localBlocksRequestMap[view][0]; 179 | } 180 | return undefined; 181 | } 182 | 183 | generateDummyBlock(QC, view) { 184 | let parentRequest = QC.request; 185 | let dummyBlocks = []; 186 | for (let v = QC.view + 1; v <= view; v++) { 187 | let block = { 188 | view: v, 189 | request: uuid(), 190 | QC: QC, 191 | parent: parentRequest, 192 | } 193 | dummyBlocks.push(block); 194 | parentRequest = block.request; 195 | } 196 | return dummyBlocks.reverse(); 197 | } 198 | 199 | proposeNextRequest(view) { 200 | // console.log("propose next request", this.view, this.lastVotedView, this.nodeID); 201 | if (this.isPrimary(view)) { 202 | let parentBlock = this.getBlockRequestByView(view); 203 | let dummyBlocks; 204 | if (parentBlock === undefined) { 205 | // this.logger.info(['generating-dummy-block', JSON.stringify(this.highQC), view]) 206 | dummyBlocks = this.generateDummyBlock(this.highQC, view); 207 | // this.logger.info(['dummy', JSON.stringify(dummyBlocks)]); 208 | if (dummyBlocks.length > 0) { 209 | parentBlock = dummyBlocks[0].request; 210 | } 211 | } 212 | 213 | const msg = { 214 | type: HotStuffMsgTypeUpdate, 215 | view: view + 1, 216 | request: uuid(), 217 | primary: getPrimaryByView(view + 1, this.nodeNum), 218 | dummyBlocks: dummyBlocks, 219 | QC: this.highQC, 220 | parent: parentBlock, 221 | sourceReplica: this.nodeID, 222 | } 223 | extendVector(this.blockVotes, view + 1); 224 | this.blockVotes[view + 1].push(msg); 225 | 226 | this.lastVotedView = view + 1; 227 | 228 | this.send(this.nodeID, 'broadcast', msg); 229 | this.updateBlock(msg); 230 | } 231 | } 232 | 233 | isAncestor(block, lockedQC) { 234 | let curBlock = block; 235 | while (curBlock.view > lockedQC.view) { 236 | let nextBlock = this.getBlockByRequest(curBlock.parent); 237 | if(nextBlock === undefined) { 238 | this.logger.info(['missing-parent-block', JSON.stringify(curBlock)]); 239 | return false; 240 | } 241 | curBlock = nextBlock; 242 | } 243 | if (curBlock.view !== lockedQC.view || curBlock.request !== lockedQC.request) { 244 | return false; 245 | } 246 | return true; 247 | } 248 | 249 | updateBlock(msg) { 250 | this.insertBlockByRequest(msg); 251 | if (msg.QC === undefined) { 252 | return false; 253 | } 254 | this.updateQCHigh(msg.QC); 255 | 256 | let parentBlock = this.getBlockByRequest(msg.QC.request); 257 | 258 | if (parentBlock === undefined || parentBlock.QC === undefined) { 259 | return false; 260 | } 261 | this.updateLockQC(parentBlock.QC); 262 | 263 | let grandParentBlock = this.getBlockByRequest(parentBlock.QC.request); 264 | 265 | if (grandParentBlock === undefined || grandParentBlock.QC === undefined || 266 | grandParentBlock.parent !== grandParentBlock.QC.request || 267 | parentBlock.parent !== parentBlock.QC.request) { 268 | // Do not commit the block if it doesn't form a three-chained 269 | return false; 270 | } 271 | 272 | // decide 273 | this.commitBlock(grandParentBlock.QC.request); 274 | } 275 | 276 | commitBlock(request) { 277 | let block = this.getBlockByRequest(request); 278 | if (block === undefined) { 279 | this.logger.info(['missing-block', 'decide', request]); 280 | return; 281 | } 282 | // console.log("commit", block, this.lastExecView) 283 | if (this.lastExecView < block.view) { 284 | if (block.parent !== undefined && block.parent != HotStuffGenesisQC) { 285 | this.commitBlock(block.parent); 286 | } 287 | this.logger.info(['decide', JSON.stringify(block)]); 288 | this.lastExecView = block.view; 289 | if (block.QC.request === block.parent) { 290 | this.decideCount++; 291 | if (this.decideCount >= 100) { 292 | this.isDecided = true; 293 | } 294 | } 295 | this.executeTimeout = this.lambda; 296 | } 297 | } 298 | 299 | voteOnBlock(msg) { 300 | if (this.isVote[msg.view] === true) { 301 | return; 302 | } 303 | extendVector(this.blockVotes, msg.view); 304 | 305 | const voteMsg = { 306 | type: HotStuffMsgTypeUpdate, 307 | view: msg.view, 308 | request: msg.request, 309 | primary: msg.primary, 310 | QC: msg.QC, 311 | sourceReplica: this.nodeID, 312 | } 313 | msg.sourceReplica = this.nodeID; 314 | if (this.blockVotes[msg.view].filter(m => m.sourceReplica === msg.sourceReplica).length === 0) { 315 | this.blockVotes[msg.view].push(msg); 316 | } 317 | if (this.nodeID !== getPrimaryByView(msg.view, this.nodeNum)) { 318 | this.send(this.nodeID, getPrimaryByView(msg.view, this.nodeNum), msg); 319 | } 320 | this.lastVotedView = msg.view; 321 | } 322 | 323 | onReceiveProposal(msg) { 324 | // a replica only votes on the first proposal it receives. 325 | if (msg.view < this.lastVotedView) { 326 | this.logger.info(['drop-msg', JSON.stringify(msg)]); 327 | return; 328 | } 329 | if (msg.tmQC !== undefined){ 330 | this.advanceViewByQC(QC); 331 | } 332 | // accepting a QC with a higher view than lockedQC to ensure liveness. 333 | // rejecting blocks contradict to locked QC to ensure safety. 334 | 335 | this.updateBlock(msg); 336 | if (msg.QC.view > this.lockedQC.view || this.isAncestor(msg, this.lockedQC)) { 337 | this.voteOnBlock(JSON.parse(JSON.stringify(msg))); 338 | } 339 | 340 | 341 | } 342 | 343 | processUpdateMsg(msg) { 344 | this.onReceiveProposal(msg); 345 | if (this.isPrimary(msg.view)) { 346 | return this.receiveVote(msg); 347 | } 348 | } 349 | 350 | 351 | registerNewNextViewInterrupt() { 352 | this.currentNextViewInterruptUUID = uuid(); 353 | // console.log("timeout", this.executeTimeout) 354 | this.registerTimeEvent({ 355 | name: HotStuffEventNextViewInterrupt, 356 | params: { uuid: this.currentNextViewInterruptUUID } 357 | }, 358 | this.executeTimeout * 1000); 359 | } 360 | 361 | onMsgEvent(msgEvent) { 362 | super.onMsgEvent(msgEvent); 363 | const msg = msgEvent.packet.content; 364 | this.logger.info(['recv', 365 | this.logger.round(msgEvent.triggeredTime), 366 | JSON.stringify(msg)]); 367 | // if (!this.checkMsgViewAndUpdateTimeout(msg, msgEvent.packet.src)) { 368 | // return; 369 | // } 370 | if (msg.type === HotStuffMsgTypeUpdate) { 371 | return this.processUpdateMsg(msg); 372 | } else if (msg.type === HotStuffMsgTypeNextView) { 373 | return this.processHotStuffNextViewMsg(msg, msgEvent.packet.src); 374 | } else { 375 | this.logger.warning(['undefined msg type']); 376 | } 377 | } 378 | 379 | isPrimary(view) { 380 | return getPrimaryByView(view, this.nodeNum) === this.nodeID; 381 | } 382 | 383 | onTimeEvent(timeEvent) { 384 | super.onTimeEvent(timeEvent); 385 | const functionMeta = timeEvent.functionMeta; 386 | // console.log('receiving time event', timeEvent) 387 | switch (functionMeta.name) { 388 | case 'start': 389 | this.start(); 390 | break; 391 | case 'issueRequest': 392 | if (this.isPrimary(this.lastVotedView+1)) { 393 | this.proposeNextRequest(this.lastVotedView + 1); 394 | } 395 | break; 396 | 397 | // Libra paceMaker: 398 | // process local timeout 399 | case HotStuffEventNextViewInterrupt: 400 | if (this.currentNextViewInterruptUUID !== undefined && 401 | this.currentNextViewInterruptUUID !== functionMeta.params.uuid) { 402 | break; 403 | } 404 | this.hotStuffViewChange(); 405 | break; 406 | default: 407 | console.log('undefined function name'); 408 | process.exit(0); 409 | } 410 | } 411 | 412 | 413 | // Libra paceMaker: 414 | // proess local timeout 415 | hotStuffViewChange() { 416 | this.logger.info([`skip a view ${this.lastVotedView}`]); 417 | this.logger.info([`doubling timeout ${this.executeTimeout}`]); 418 | this.lastVotedView ++; 419 | this.executeTimeout *= 2; 420 | this.view++; 421 | 422 | 423 | const nextPrimary = getPrimaryByView(this.lastVotedView, this.nodeNum); 424 | // Similar to timeout QC in Libra 425 | const msg = { 426 | type: HotStuffMsgTypeNextView, 427 | view: this.lastVotedView, 428 | primary: nextPrimary, 429 | QC: this.highQC, 430 | sourceReplica: this.nodeID, 431 | } 432 | if (this.nextView[msg.view] === undefined) { 433 | this.nextView[msg.view] = []; 434 | } 435 | this.nextView[msg.view].push(msg); 436 | this.registerNewNextViewInterrupt(msg); 437 | this.send(this.nodeID, 'broadcast', msg); 438 | this.processHotStuffNextViewMsg(msg, this.nodeID); 439 | } 440 | 441 | // paceMaker: advance_round 442 | advanceViewByQC(QC) { 443 | if (QC.view < this.lastVotedView) { 444 | return; 445 | } 446 | this.logger.info(['advance-view', JSON.stringify(QC)]); 447 | this.lastVotedView = QC.view + 1; 448 | const primary = getPrimaryByView(QC.view, this.nodeNum); 449 | if (this.nodeID != primary) { 450 | // send QC to primary 451 | const msg = { 452 | type: HotStuffMsgTypeNextView, 453 | view: QC.view, 454 | primary: primary, 455 | QC: QC, 456 | sourceReplica: this.nodeID, 457 | } 458 | if (this.nextView[msg.view] === undefined) { 459 | this.nextView[msg.view] = []; 460 | } 461 | this.nextView[msg.view].push(msg); 462 | this.registerNewNextViewInterrupt(msg); 463 | this.send(this.nodeID, primary, msg); 464 | } 465 | } 466 | 467 | // This is the combination of two function 468 | // nextViewMsg in hotstuff and process remotetimeout in Libra's pacemaker 469 | processHotStuffNextViewMsg(msg, sourceReplica) { 470 | if (msg.view < this.lastVotedView) { 471 | return; 472 | } 473 | 474 | this.logger.info(['process-next-view', JSON.stringify(msg)]); 475 | // if (!this.isPrimary(msg.view)) { 476 | // return; 477 | // } 478 | if (this.nextView[msg.view] === undefined) { 479 | this.nextView[msg.view] = []; 480 | } 481 | msg.sourceReplica = sourceReplica; 482 | if (this.nextView[msg.view].filter(m => m.sourceReplica === msg.sourceReplica).length == 0) { 483 | this.nextView[msg.view].push(msg); 484 | } 485 | 486 | if (this.nextView[msg.view].length >= this.nodeNum - this.f) { 487 | // process remote QC 488 | this.logger.info(['process-remote qc', JSON.stringify(msg)]) 489 | const QC = { 490 | view: msg.view, 491 | request: 'pacemaker-timeout-QC', 492 | } 493 | if (this.isPrimary(msg.view)){ 494 | this.proposeNextRequest(msg.view); 495 | } else { 496 | this.advanceViewByQC(QC); 497 | } 498 | } 499 | } 500 | 501 | start() { 502 | if (this.isPrimary(this.lastVotedView )) { 503 | this.proposeNextRequest(this.lastVotedView); 504 | } 505 | } 506 | 507 | constructor(nodeID, nodeNum, network, registerTimeEvent, customized_config) { 508 | super(nodeID, nodeNum, network, registerTimeEvent); 509 | if (customized_config !== undefined) { 510 | config = customized_config; 511 | } 512 | this.f = (this.nodeNum % 3 === 0) ? 513 | this.nodeNum / 3 - 1 : Math.floor(this.nodeNum / 3); 514 | // check if a node receive a request in time 515 | this.lambda = config.lambda; 516 | this.executeTimeout = this.lambda; 517 | // log 518 | 519 | this.viewChange = []; 520 | 521 | this.isDecided = false; 522 | this.lastVotedView = -1; 523 | this.lastExecView = -1; 524 | this.localBlocksRequestMap = {}; 525 | 526 | this.prepareQC = HotStuffGenesisQC; 527 | this.lockedQC = HotStuffGenesisQC; 528 | this.commitQC = HotStuffGenesisQC; 529 | this.highQC = HotStuffGenesisQC; 530 | 531 | this.isBroadcastMap = {}; 532 | this.blockVotes = {}; 533 | // this.isBroadcastMap = {}; 534 | 535 | this.decideCount = 0; 536 | this.blockVotes = {}; 537 | this.isVote = {}; 538 | 539 | this.insertBlockByRequest(HotStuffGenesisQC); 540 | this.nextView = {}; 541 | this.registerNewNextViewInterrupt(); 542 | this.registerTimeEvent({ name: 'start', params: {} }, 0); 543 | } 544 | } 545 | //const n = new PBFTNode(process.argv[2], process.argv[3]); 546 | module.exports = HotStuffTMNode; 547 | -------------------------------------------------------------------------------- /ba-algo/basic-hotstuff.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('./node'); 4 | const uuid = require('uuid/v4'); 5 | const config = require('../config'); 6 | 7 | const HotStuffMsgTypePrepare = 'hot-stuff-prepare'; 8 | const HotStuffMsgTypePreCommit = 'hot-stuff-pre-commit'; 9 | const HotStuffMsgTypeCommit = 'hot-stuff-commit'; 10 | const HotStuffMsgTypeDecide = 'hot-stuff-decide'; 11 | const HotStuffMsgTypeNextView = 'hot-stuff-next-view'; 12 | const HotStuffEventNextViewInterrupt = 'hot-stuff-next-view-interrupt'; 13 | 14 | function extendVector(v, n) { 15 | if (v[n] === undefined) { 16 | v[n] = []; 17 | } 18 | } 19 | 20 | // extend vector v to be able to access v[n][m] = array 21 | function extendVector2D(v, n, m) { 22 | if (v[n] === undefined) { 23 | extendVector(v, n); 24 | } 25 | if (v[n][m] === undefined) { 26 | extendVector(v[n], m); 27 | } 28 | } 29 | 30 | function getPrimaryByView(view, nodeNum) { 31 | return (view % nodeNum + 1).toString(); 32 | } 33 | 34 | class HotStuffNode extends Node { 35 | // safeNodePredicate 36 | checkMsgViewAndUpdateTimeout(msg, sourceReplica) { 37 | if (msg.type === HotStuffMsgTypeDecide) { 38 | return true; 39 | } 40 | if (msg.view != this.view) { 41 | this.logger.info(['dropping-msg', this.view, msg.view, JSON.stringify(msg), sourceReplica]); 42 | return false; 43 | } 44 | 45 | 46 | if (this.lockedQC.view === undefined || this.lockedQC.n === undefined) { 47 | // no lockedQC 48 | return true; 49 | } 50 | 51 | 52 | 53 | if (msg.n <= this.lockedQC.n && msg.reqeust !== this.lockedQC.reqeust && !(QC !== undefined && QC.view > this.lockedQC.n)) { 54 | // console.log("safenode prdicate", msg, this.lockedQC); 55 | this.logger.info(["locked", JSON.stringify(msg), JSON.stringify(this.lockedQC)]); 56 | return false; 57 | } 58 | 59 | // if (QC !== undefined && QC.view > this.view) { 60 | // // to ensure liveness 61 | // // if a replica see a QC with a higher view, it changes its mind. 62 | // this.logger.info(['unlock', JSON.stringify(QC), JSON.stringify(msg)]); 63 | // this.view = QC.view; 64 | // this.registerNewNextViewInterrupt(msg); 65 | // return true; 66 | // } 67 | 68 | 69 | // liveliness 70 | // this.logger.info([`update view from: ${this.view} to ${msg.view}`, JSON.stringify(msg)]); 71 | // this.view = msg.view; 72 | return true 73 | } 74 | 75 | registerNewNextViewInterrupt(msg) { 76 | this.currentNextViewInterruptUUID = uuid(); 77 | // console.log("timeout", this.executeTimeout) 78 | this.logger.info(['extend-timeout', this.executeTimeout * 1000, this.currentNextViewInterruptUUID]) 79 | this.registerTimeEvent({ 80 | name: HotStuffEventNextViewInterrupt, 81 | params: { request: msg.request, view: msg.view, uuid: this.currentNextViewInterruptUUID } 82 | }, 83 | this.executeTimeout * 1000); 84 | } 85 | 86 | isPrimary(view) { 87 | return getPrimaryByView(view, this.nodeNum) === this.nodeID; 88 | } 89 | 90 | // when primary receives enough vote on prepare 91 | sendPreCommit(msg) { 92 | // sending prepareQC and preCommit Msg 93 | let signers = this.prepare[msg.view][msg.n].filter(prepareMsg => prepareMsg.request === msg.request) 94 | .map(prepareMsg => { 95 | return prepareMsg.sourceReplica 96 | }) 97 | const parepareQC = { 98 | n: msg.n, 99 | request: msg.request, 100 | view: msg.view, 101 | signers: signers, 102 | } 103 | 104 | const preCommitMsg = { 105 | type: HotStuffMsgTypePreCommit, 106 | view: msg.view, 107 | n: msg.n, 108 | request: msg.request, 109 | primary: this.nodeID, 110 | QC: parepareQC, 111 | sourceReplica: this.nodeID, 112 | }; 113 | 114 | this.preCommitRequest(preCommitMsg) 115 | extendVector2D(this.preCommit, preCommitMsg.view, preCommitMsg.n); 116 | this.preCommit[preCommitMsg.view][preCommitMsg.n].push(preCommitMsg) 117 | this.send(this.nodeID, 'broadcast', preCommitMsg); 118 | } 119 | 120 | sendCommit(msg) { 121 | // send preCommit QC and commit msg 122 | // on receiving precommit QC, the replica should lock the value. 123 | // sending prepareQC and preCommit Msg 124 | let signers = this.preCommit[msg.view][msg.n].filter(preCommitMsg => preCommitMsg.request === msg.request) 125 | .map(preCommitMsg => { 126 | return preCommitMsg.sourceReplica 127 | }); 128 | const preCommitQC = { 129 | n: msg.n, 130 | request: msg.request, 131 | view: msg.view, 132 | signers: signers, 133 | }; 134 | const commitMsg = { 135 | type: HotStuffMsgTypeCommit, 136 | view: this.view, 137 | n: msg.n, 138 | request: msg.request, 139 | primary: this.nodeID, 140 | QC: preCommitQC, 141 | sourceReplica: this.nodeID, 142 | }; 143 | this.commitRequest(commitMsg) 144 | extendVector2D(this.commit, commitMsg.view, commitMsg.n); 145 | this.commit[msg.view][msg.n].push(commitMsg) 146 | this.send(this.nodeID, 'broadcast', commitMsg); 147 | } 148 | 149 | sendDecideMsg(msg) { 150 | let signers = this.commit[msg.view][msg.n].filter(commitMsg => commitMsg.request === msg.request) 151 | .map(commitMsg => { 152 | return commitMsg.sourceReplica 153 | }); 154 | const commitQC = { 155 | n: msg.n, 156 | request: msg.request, 157 | view: msg.view, 158 | signers: signers, 159 | }; 160 | const decideMsg = { 161 | type: HotStuffMsgTypeDecide, 162 | n: msg.n, 163 | view: msg.view, 164 | request: msg.request, 165 | i: this.nodeID, 166 | QC: commitQC, 167 | sourceReplica: this.nodeID, 168 | }; 169 | this.send(this.nodeID, 'broadcast', decideMsg); 170 | } 171 | 172 | processHotStuffDecide(msg, sourceReplica) { 173 | if (this.isRequestDecided(msg.view, msg.n)) { 174 | return; 175 | } 176 | // should verify wether the QC is valid. 177 | this.decideRequest(msg); 178 | } 179 | 180 | processHotStuffCommit(msg, sourceReplica) { 181 | // push commit 182 | extendVector2D(this.commit, msg.view, msg.n); 183 | msg.sourceReplica = sourceReplica 184 | if (this.commit[msg.view][msg.n].filter(m => m.sourceReplica === msg.sourceReplica).length == 0) { 185 | this.commit[msg.view][msg.n].push(msg); 186 | } 187 | 188 | // check committed local 189 | if (this.isPrimary(msg.view)) { 190 | if (this.commit[msg.view][msg.n].length >= this.nodeNum - this.f) { 191 | this.lastDecidedSeq = msg.n; 192 | this.lastDecidedRequest = msg.reqeust; 193 | this.logger.info(['decide', msg.request]); 194 | this.isDecided = true; 195 | //console.log(`${this.nodeID} decides`); 196 | if (!this.isRequestDecided(msg.view, msg.n)) { 197 | this.decideRequest(msg) 198 | this.sendDecideMsg(msg); 199 | 200 | } 201 | } 202 | return; 203 | } 204 | if (!this.isRequestCommit(msg)) { 205 | this.commitRequest(msg); 206 | msg.sourceReplica = this.nodeID; 207 | this.send(this.nodeID, msg.primary, msg); 208 | } 209 | } 210 | 211 | processHotStuffPreCommit(msg, sourceReplica) { 212 | extendVector2D(this.preCommit, msg.view, msg.n); 213 | // save prepareQC 214 | msg.sourceReplica = sourceReplica; 215 | if (this.preCommit[msg.view][msg.n].filter(m => m.sourceReplica === msg.sourceReplica).length == 0) { 216 | this.preCommit[msg.view][msg.n].push(msg); 217 | } 218 | 219 | if(this.isPrimary(msg.view)) { 220 | if (this.preCommit[msg.view][msg.n].length >= this.nodeNum - this.f) { 221 | if (!this.isRequestCommit(msg.view, msg.n)) { 222 | this.sendCommit(msg) 223 | } 224 | } 225 | return 226 | } 227 | 228 | if (!this.isRequestPrecommit(msg.view, msg.n)) { 229 | this.preCommitRequest(msg); 230 | msg.sourceReplica = this.nodeID; 231 | this.send(this.nodeID, msg.primary, msg); 232 | } 233 | } 234 | 235 | processHotStuffPrepare(msg, sourceReplica) { 236 | 237 | extendVector2D(this.prepare, msg.view, msg.n) 238 | // msg.sourceReplica = sourceReplica 239 | if (this.prepare[msg.view][msg.n].filter(m => m.sourceReplica === msg.sourceReplica).length == 0) { 240 | this.prepare[msg.view][msg.n].push(msg) 241 | } 242 | 243 | if (this.isPrimary(msg.view)) { 244 | // todo: we make sure the msg have collected enough votes by checking the threshold sig 245 | if(this.prepare[msg.view][msg.n].filter(m => {return m.request === msg.request}).length >= this.nodeNum - this.f) { 246 | if (!this.isRequestPrecommit(msg.view, msg.n)) { 247 | this.sendPreCommit(msg) 248 | } 249 | } 250 | return 251 | } 252 | if (!this.isRequestPrepared(msg.view, msg.n)) { 253 | this.prepareRequest(msg); 254 | msg.sourceReplica = this.nodeID; 255 | this.send(this.nodeID, msg.primary, msg); 256 | } 257 | } 258 | 259 | onMsgEvent(msgEvent) { 260 | super.onMsgEvent(msgEvent); 261 | const msg = msgEvent.packet.content; 262 | this.logger.info(['recv', 263 | this.logger.round(msgEvent.triggeredTime), 264 | JSON.stringify(msg)]); 265 | if (!this.checkMsgViewAndUpdateTimeout(msg, msgEvent.packet.src)) { 266 | return; 267 | } 268 | if (msg.type === HotStuffMsgTypePrepare) { 269 | return this.processHotStuffPrepare(msg, msgEvent.packet.src); 270 | } else if (msg.type === HotStuffMsgTypePreCommit) { 271 | return this.processHotStuffPreCommit(msg, msgEvent.packet.src); 272 | } else if (msg.type === HotStuffMsgTypeCommit) { 273 | return this.processHotStuffCommit(msg, msgEvent.packet.src); 274 | } else if (msg.type === HotStuffMsgTypeDecide) { 275 | return this.processHotStuffDecide(msg, msgEvent.packet.src); 276 | } else if (msg.type === HotStuffMsgTypeNextView) { 277 | return this.processHotStuffNextViewMsg(msg, msgEvent.packet.src); 278 | } else { 279 | this.logger.warning(['undefined msg type']); 280 | } 281 | } 282 | 283 | onTimeEvent(timeEvent) { 284 | super.onTimeEvent(timeEvent); 285 | const functionMeta = timeEvent.functionMeta; 286 | // console.log('receiving time event', timeEvent) 287 | switch (functionMeta.name) { 288 | case 'start': 289 | this.start(); 290 | break; 291 | case 'issueRequest': 292 | if (this.isPrimary(this.view)) { 293 | this.issueRequest(); 294 | } 295 | break; 296 | case HotStuffEventNextViewInterrupt: 297 | if (this.currentNextViewInterruptUUID !== undefined && 298 | this.currentNextViewInterruptUUID !== functionMeta.params.uuid) { 299 | break; 300 | } 301 | this.logger.info([timeEvent.triggeredTime, 'not executed in time', JSON.stringify(functionMeta.params)]); 302 | this.hotStuffViewChange(functionMeta.params); 303 | break; 304 | default: 305 | console.log('undefined function name'); 306 | process.exit(0); 307 | } 308 | } 309 | 310 | 311 | hotStuffViewChange(params) { 312 | this.logger.info([`start a view change to ${this.view+1}`]); 313 | this.logger.info([`doubling timeout ${this.executeTimeout}`]); 314 | this.executeTimeout *= 2; 315 | this.view++; 316 | const nextPrimary = getPrimaryByView(this.view, this.nodeNum); 317 | const nextViewMsg = { 318 | type: HotStuffMsgTypeNextView, 319 | view: this.view, 320 | QC: this.highQC, 321 | n: this.seq, 322 | sourceReplica: this.nodeID, 323 | } 324 | if (nextPrimary === this.nodeID) { 325 | this.processHotStuffNextViewMsg(nextViewMsg, this.nodeID); 326 | } else { 327 | extendVector2D(this.nextView, nextViewMsg.view, nextViewMsg.n); 328 | this.nextView[nextViewMsg.view][nextViewMsg.n].push(nextViewMsg); 329 | this.send(this.nodeID, nextPrimary.toString(), nextViewMsg); 330 | } 331 | this.registerNewNextViewInterrupt(nextViewMsg); 332 | } 333 | 334 | processHotStuffNextViewMsg(msg, sourceReplica) { 335 | if (getPrimaryByView(msg.view, this.nodeNum) !== this.nodeID){ 336 | return; 337 | } 338 | 339 | extendVector(this.nextView, msg.view); 340 | msg.sourceReplica = sourceReplica; 341 | if (this.nextView[msg.view].filter(m => m.sourceReplica === msg.sourceReplica).length == 0) { 342 | this.nextView[msg.view].push(msg); 343 | } 344 | 345 | if (this.nextView[msg.view].length >= this.nodeNum - this.f) { 346 | if (!this.isIssueRequest(msg.view)) { 347 | this.issueRequest(msg.view); 348 | this.setIssueRequest(msg.view); 349 | } 350 | } 351 | } 352 | 353 | setIssueRequest(view) { 354 | this.isBroadcast[view] = true; 355 | } 356 | isIssueRequest(view) { 357 | if (this.isBroadcast[view] === true) { 358 | return true; 359 | } 360 | return false; 361 | } 362 | 363 | receiveRequest(msg) { 364 | this.localCommandMap[msg.n] = msg.request; 365 | extendVector2D(this.digest, msg.view, msg.n); 366 | if (this.digest[msg.view][msg.n] === undefined) { 367 | this.digest[msg.view][msg.n] = {}; 368 | // // work around 369 | // if(this.seq != msg.n) { 370 | // this.seq = msg.n; 371 | // } 372 | } 373 | this.digest[msg.view][msg.n].isReceived = true 374 | } 375 | 376 | updateHighQC(QC) { 377 | if(this.highQC === undefined) { 378 | this.highQC = QC; 379 | } 380 | if (QC.view > this.highQC.view) { 381 | this.highQC = QC; 382 | } 383 | } 384 | 385 | prepareRequest(msg) { 386 | this.localCommandMap[msg.n] = msg.request; 387 | extendVector2D(this.digest, msg.view, msg.n); 388 | if (this.digest[msg.view][msg.n] === undefined) { 389 | this.digest[msg.view][msg.n] = {}; 390 | } 391 | this.digest[msg.view][msg.n].isPrepared = true 392 | 393 | this.logger.info(['prepare-request', `prepare request: ${JSON.stringify(msg)}`]); 394 | } 395 | 396 | commitRequest(msg) { 397 | extendVector2D(this.digest, msg.view, msg.n); 398 | if (this.digest[msg.view][msg.n] === undefined) { 399 | this.digest[msg.view][msg.n] = {}; 400 | } 401 | this.digest[msg.view][msg.n].isCommit = true; 402 | this.logger.info(['locked QC', JSON.stringify(msg)]) 403 | this.lockedQC = msg.QC; 404 | } 405 | 406 | preCommitRequest(msg) { 407 | extendVector2D(this.digest, msg.view, msg.n); 408 | if (this.digest[msg.view][msg.n] === undefined) { 409 | this.digest[msg.view][msg.n] = {}; 410 | } 411 | this.digest[msg.view][msg.n].isPreCommit = true; 412 | if (msg.QC !== undefined) { 413 | this.updateHighQC(msg.QC); 414 | } 415 | } 416 | 417 | 418 | 419 | decideRequest(msg) { 420 | extendVector2D(this.digest, msg.view, msg.n); 421 | if (this.digest[msg.view][msg.n] === undefined) { 422 | this.digest[msg.view][msg.n] = {}; 423 | } 424 | this.digest[msg.view][msg.n].isDecided = true; 425 | this.logger.info(['decide', JSON.stringify(msg)]); 426 | this.seq++; 427 | 428 | this.lastDecidedSeq = msg.n; 429 | this.lastDecidedRequest = msg.reqeust; 430 | this.logger.info(['decide', msg.request, this.decideCount]); 431 | this.isDecided = true; 432 | this.decideCount++; 433 | this.executeTimeout = 1; 434 | if (this.isPrimary(this.view)) { 435 | this.issueRequest(); 436 | } 437 | this.registerNewNextViewInterrupt(msg); 438 | } 439 | 440 | 441 | isRequestRecived(view, n) { 442 | extendVector2D(this.digest, view, n); 443 | if (this.digest[view][n] !== undefined && this.digest[view][n].isReceived) { 444 | return true; 445 | } 446 | return false; 447 | } 448 | 449 | isRequestCommit(view, n) { 450 | extendVector2D(this.digest, view, n); 451 | if (this.digest[view][n] !== undefined && this.digest[view][n].isCommit) { 452 | return true; 453 | } 454 | return false; 455 | } 456 | 457 | isRequestPrecommit(view, n) { 458 | extendVector2D(this.digest, view, n); 459 | if (this.digest[view][n] !== undefined && this.digest[view][n].isPreCommit) { 460 | return true; 461 | } 462 | return false; 463 | } 464 | 465 | 466 | isRequestPrepared(view, n) { 467 | extendVector2D(this.digest, view, n); 468 | if (this.digest[view][n] !== undefined && this.digest[view][n].isPrepared) { 469 | return true; 470 | } 471 | return false; 472 | } 473 | 474 | isRequestDecided(view, n) { 475 | extendVector2D(this.digest, view, n); 476 | if (this.digest[view][n] !== undefined && this.digest[view][n].isDecided) { 477 | return true; 478 | } 479 | return false; 480 | } 481 | 482 | issueRequest(view) { 483 | let request = uuid(); 484 | if (this.nextView[view] !== undefined && 485 | this.nextView[view].length >= this.nodeNum - this.f) { 486 | // should get the highest n from all prepare QC 487 | const maxNMsg = this.nextView[this.view].maxBy(msg => { 488 | if(msg.QC !== undefined) { 489 | return msg.QC.n; 490 | } 491 | return -1; 492 | }); 493 | this.logger.info(['maxNMSG', JSON.stringify(maxNMsg)]); 494 | if (maxNMsg.QC !== undefined && maxNMsg.QC.request !== undefined) { 495 | request = maxNMsg.QC.request; 496 | this.updateHighQC(maxNMsg.QC); 497 | } 498 | } 499 | 500 | const hotStuffPrepareMsg = { 501 | type: HotStuffMsgTypePrepare, 502 | view: this.view, 503 | n: this.seq, 504 | request: request, 505 | primary: this.nodeID, 506 | sourceReplica: this.nodeID, 507 | QC: this.highQC, 508 | }; 509 | 510 | 511 | this.prepareRequest(hotStuffPrepareMsg) 512 | extendVector2D(this.prepare, this.view, hotStuffPrepareMsg.n); 513 | this.prepare[hotStuffPrepareMsg.view][hotStuffPrepareMsg.n].push(hotStuffPrepareMsg); 514 | this.send(this.nodeID, 'broadcast', hotStuffPrepareMsg); 515 | } 516 | 517 | start() { 518 | if (this.isPrimary(this.view)) { 519 | this.issueRequest(); 520 | } 521 | const msg = { 522 | } 523 | this.registerNewNextViewInterrupt(msg) 524 | } 525 | 526 | constructor(nodeID, nodeNum, network, registerTimeEvent) { 527 | super(nodeID, nodeNum, network, registerTimeEvent); 528 | this.f = (this.nodeNum % 3 === 0) ? 529 | this.nodeNum / 3 - 1 : Math.floor(this.nodeNum / 3); 530 | // pbft 531 | this.view = 0; 532 | this.seq = 0; 533 | // view change 534 | // check if a node receive a request in time 535 | this.lambda = config.lambda; 536 | this.executeTimeout = this.lambda; 537 | // this makes nodes create checkpoint at n = 0 538 | this.lastStableCheckpoint = 0; 539 | // log 540 | this.digest = {}; 541 | this.prepare = []; 542 | this.preCommit = []; 543 | this.commit = []; 544 | this.viewChange = []; 545 | this.prepareQC = {}; 546 | this.lockedQC = {}; 547 | this.nextView = {}; 548 | this.localCommandMap = {}; 549 | this.highestRequestEventView = {}; 550 | this.isBroadcast = {} 551 | this.decideCount = 0; 552 | this.registerTimeEvent({ name: 'start', params: {} }, 0); 553 | } 554 | } 555 | //const n = new PBFTNode(process.argv[2], process.argv[3]); 556 | module.exports = HotStuffNode; -------------------------------------------------------------------------------- /ba-algo/pbft.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Node = require('./node'); 4 | const uuid = require('uuid/v4'); 5 | const config = require('../config'); 6 | 7 | class PBFTNode extends Node { 8 | // extend vector v to be able to access v[n] = array 9 | extendVector(v, n) { 10 | if (v[n] === undefined) { 11 | v[n] = []; 12 | } 13 | } 14 | // extend vector v to be able to access v[n][m] = array 15 | extendVector2D(v, n, m) { 16 | if (v[n] === undefined) { 17 | this.extendVector(v, n); 18 | } 19 | if (v[n][m] === undefined) { 20 | this.extendVector(v[n], m); 21 | } 22 | } 23 | isPrepared(d, v, n) { 24 | // m is in log 25 | // pre-prepare is in log 26 | // 2f + 1 prepare is in log that match pre-prepare 27 | if (this.digest[d] !== undefined && 28 | this.prePrepare[v][n][0] !== undefined) { 29 | const d = this.prePrepare[v][n][0].d; 30 | const count = this.prepare[v][n].filter(msg => (msg.d === d)).length; 31 | return (count >= 2 * this.f + 1); 32 | } 33 | return false; 34 | } 35 | isCommittedLocal(d, v, n) { 36 | // isPrepared(d, v, n) is true 37 | // 2f + 1 commit is in log that match pre-prepare 38 | if (this.isPrepared(d, v, n)) { 39 | const d = this.prePrepare[v][n][0].d; 40 | const count = this.commit[v][n].filter(msg => (msg.d === d)).length; 41 | return (count >= 2 * this.f + 1); 42 | } 43 | return false; 44 | } 45 | isStableCheckpoint(n) { 46 | if (this.checkpoint[n] === undefined || 47 | this.checkpoint[n].length === 0) { 48 | return false; 49 | } 50 | const count = this.checkpoint[n].groupBy(msg => msg.d) 51 | .map(e => e[1].length) 52 | .max(); 53 | return (count >= 2 * this.f + 1); 54 | } 55 | 56 | handlePrePrepareMsg(msg) { 57 | // check signature, view, sequence number unique and its range 58 | if (msg.v !== this.view) { 59 | return; 60 | } 61 | // push pre-prepare 62 | this.extendVector2D(this.prePrepare, msg.v, msg.n); 63 | // pre-prepare[v][n] should only have one message 64 | if (this.prePrepare[msg.v][msg.n].length === 0) { 65 | //clearTimeout(this.receiveTimer); 66 | this.hasReceiveRequest = true; 67 | if (msg === undefined) { console.log("!! 67"); process.exit(0); } 68 | this.prePrepare[msg.v][msg.n].push(msg); 69 | if (this.digest[msg.d] === undefined) { 70 | this.digest[msg.d] = { 71 | isReceived: true, 72 | isPrepared: false, 73 | isDecided: false, 74 | }; 75 | this.registerTimeEvent( 76 | { name: 'executeTimeout', params: { d: msg.d, v: msg.v } }, 77 | this.executeTimeout * 1000 78 | ); 79 | } 80 | // send prepare 81 | const prepareMsg = { 82 | type: 'prepare', 83 | v: msg.v, 84 | n: msg.n, 85 | d: msg.d, 86 | i: this.nodeID 87 | }; 88 | this.extendVector2D(this.prepare, msg.v, msg.n); 89 | this.prepare[msg.v][msg.n].push(prepareMsg); 90 | this.send(this.nodeID, 'broadcast', prepareMsg); 91 | } 92 | else { 93 | console.log(`${this.nodeID}, normal prepare conflict`); 94 | console.log('1', this.prePrepare[msg.v][msg.n][0]); 95 | console.log('2', msg); 96 | this.logger.warning(['normal pre-prepare conflict']); 97 | } 98 | } 99 | 100 | handlePrepareMsg(msg) { 101 | // check signature, view, sequence number unique and its range 102 | if (msg.v !== this.view) { 103 | return; 104 | } 105 | // push prepare 106 | this.extendVector2D(this.prePrepare, msg.v, msg.n); 107 | this.extendVector2D(this.prepare, msg.v, msg.n); 108 | // prepare may contain msg with different digests 109 | this.prepare[msg.v][msg.n].push(msg); 110 | if (this.digest[msg.d] && this.digest[msg.d].isPrepared) { 111 | return; 112 | } 113 | if (this.isPrepared(msg.d, msg.v, msg.n)) { 114 | this.digest[msg.d].isPrepared = true; 115 | const commitMsg = { 116 | type: 'commit', 117 | v: msg.v, 118 | n: msg.n, 119 | d: msg.d, 120 | i: this.nodeID 121 | }; 122 | this.extendVector2D(this.commit, msg.v, msg.n); 123 | this.commit[msg.v][msg.n].push(commitMsg); 124 | this.send(this.nodeID, 'broadcast', commitMsg); 125 | } 126 | } 127 | 128 | onMsgEvent(msgEvent) { 129 | super.onMsgEvent(msgEvent); 130 | const msg = msgEvent.packet.content; 131 | this.logger.info(['recv', 132 | this.logger.round(msgEvent.triggeredTime), 133 | JSON.stringify(msg)]); 134 | if (this.isInViewChange && 135 | (msg.type !== 'checkpoint' && 136 | msg.type !== 'view-change' && 137 | msg.type !== 'new-view' && 138 | msg.type !== 'decide')) { 139 | return; 140 | } 141 | if (msg.type === 'pre-prepare') { 142 | this.handlePrePrepareMsg(msg); 143 | } 144 | else if (msg.type === 'prepare') { 145 | this.handlePrepareMsg(msg); 146 | } 147 | else if (msg.type === 'commit') { 148 | // check signature, view, sequence number unique and its range 149 | if (msg.v !== this.view) { 150 | return; 151 | } 152 | // push commit 153 | this.extendVector2D(this.prePrepare, msg.v, msg.n); 154 | this.extendVector2D(this.prepare, msg.v, msg.n); 155 | this.extendVector2D(this.commit, msg.v, msg.n); 156 | this.commit[msg.v][msg.n].push(msg); 157 | if (this.digest[msg.d] && this.digest[msg.d].isDecided) { 158 | return; 159 | } 160 | // check committed local 161 | if (this.isCommittedLocal(msg.d, msg.v, msg.n)) { 162 | //clearTimeout(this.digest[msg.d].timer); 163 | this.digest[msg.d].isDecided = true; 164 | this.lastDecidedSeq = msg.n; 165 | this.lastDecidedRequest = msg.d; 166 | this.logger.info(['decide', Math.round(this.clock), msg.d]); 167 | this.isDecided = true; 168 | const decideMsg = { 169 | type: 'decide', 170 | n: msg.n, 171 | d: msg.d, 172 | i: this.nodeID, 173 | proof: this.commit[msg.v][msg.n].filter(comMsg => (comMsg.d === msg.d)) 174 | }; 175 | this.send(this.nodeID, 'broadcast', decideMsg); 176 | if (msg.n % this.checkpointPeriod === 0) { 177 | const checkpointMsg = { 178 | type: 'checkpoint', 179 | n: msg.n, 180 | d: msg.d, 181 | i: this.nodeID 182 | }; 183 | this.extendVector(this.checkpoint, msg.n); 184 | this.checkpoint[msg.n].push(checkpointMsg); 185 | this.send(this.nodeID, 'broadcast', checkpointMsg); 186 | } 187 | } 188 | } 189 | else if (msg.type === 'decide') { 190 | if (this.digest[msg.d] && this.digest[msg.d].isDecided) { 191 | return; 192 | } 193 | if (this.digest[msg.d] === undefined) { 194 | this.digest[msg.d] = { 195 | isReceived: true, 196 | isPrepared: true, 197 | isDecided: true, 198 | }; 199 | } 200 | this.digest[msg.d].isDecided = true; 201 | this.lastDecidedSeq = msg.n; 202 | this.lastDecidedRequest = msg.d; 203 | this.logger.info(['decide', msg.d]); 204 | this.isDecided = true; 205 | const decideMsg = { 206 | type: 'decide', 207 | n: msg.n, 208 | d: msg.d, 209 | i: this.nodeID, 210 | proof: msg.proof 211 | }; 212 | this.send(this.nodeID, 'broadcast', decideMsg); 213 | } 214 | else if (msg.type === 'checkpoint') { 215 | this.extendVector(this.checkpoint, msg.n); 216 | this.checkpoint[msg.n].push(msg); 217 | // earliest checkpoint that is not stable 218 | let usCheckpoint = 219 | this.lastStableCheckpoint + this.checkpointPeriod; 220 | if (msg.n === usCheckpoint) { 221 | while (this.isStableCheckpoint(usCheckpoint)) { 222 | this.logger.info([`create stable checkpoint ${usCheckpoint}`]); 223 | this.lastStableCheckpoint = usCheckpoint; 224 | usCheckpoint += this.checkpointPeriod; 225 | } 226 | } 227 | } 228 | else if (msg.type === 'view-change') { 229 | // somehow verify this is a reasonable view change msg 230 | // checkpoint proof is provided 231 | if (msg.v <= this.view) return; 232 | this.extendVector(this.viewChange, msg.v); 233 | this.viewChange[msg.v].push(msg); 234 | if (this.viewChange[msg.v].length >= this.f + 1 && 235 | !this.isInViewChange && msg.v > this.view) { 236 | this.startViewChange(msg.v); 237 | } 238 | if (this.viewChange[msg.v].length >= 2 * this.f + 1 && 239 | (msg.v % this.nodeNum) === (parseInt(this.nodeID) - 1) && 240 | !this.isPrimary) { 241 | this.logger.info(['start as a primary']); 242 | this.isPrimary = true; 243 | this.isInViewChange = false; 244 | this.view = msg.v; 245 | let minS = this.viewChange[msg.v] 246 | .map(msg => msg.n) 247 | .max(); 248 | //minS = minS < 0 ? 0 : minS; 249 | const allPrePrepare = this.viewChange[msg.v] 250 | .map(msg => msg.P) 251 | .map(P => P.map(Pm => Pm['pre-prepare'])) 252 | .flat(); 253 | let maxS = (allPrePrepare.length === 0) ? 254 | minS : allPrePrepare.map(msg => msg.n).max(); 255 | //maxS = maxS < 0 ? 0 : maxS; 256 | const O = []; 257 | this.newViewPrepareMsgs = []; 258 | for (let n = minS + 1; n <= maxS; n++) { 259 | const pmsg = allPrePrepare.find(msg => msg.n === n); 260 | const d = (pmsg === undefined) ? 'nop' : pmsg.d; 261 | // re-consensus d 262 | this.digest[d] = { 263 | isReceived: true, 264 | isPrepared: false, 265 | isDecided: false, 266 | }; 267 | const prePrepareMsg = { 268 | type: 'pre-prepare', 269 | v: msg.v, 270 | n: n, 271 | d: d 272 | }; 273 | this.extendVector2D(this.prePrepare, msg.v, n); 274 | if (prePrepareMsg === undefined) { console.log("!! 274"); process.exit(0); } 275 | this.prePrepare[msg.v][n].push(prePrepareMsg); 276 | const prepareMsg = { 277 | type: 'prepare', 278 | v: msg.v, 279 | n: n, 280 | d: d, 281 | i: this.nodeID 282 | }; 283 | this.extendVector2D(this.prepare, msg.v, n); 284 | this.prepare[msg.v][n].push(prepareMsg); 285 | // broadcast this after every node enter view v 286 | this.newViewPrepareMsgs.push(prepareMsg); 287 | O.push({ 288 | v: msg.v, 289 | n: n, 290 | d: d 291 | }); 292 | } 293 | this.registerTimeEvent( 294 | { name: 'broadcastNewViewPrepare' }, 295 | this.lambda * 1000 296 | ); 297 | // next seq starts from maxS + 1 298 | this.seq = maxS + 1; 299 | const [prePrepareMsg, prepareMsg] = this.genRequest(); 300 | const newViewMsg = { 301 | type: 'new-view', 302 | v: msg.v, 303 | V: this.viewChange[msg.v], 304 | O: O, 305 | i: this.nodeID, 306 | prePrepareMsg, 307 | prepareMsg, 308 | }; 309 | this.send(this.nodeID, 'broadcast', newViewMsg); 310 | // start as primary after every node enter view v 311 | // this.registerTimeEvent( 312 | // { name: 'issueRequest' }, 313 | // this.lambda * 1000 314 | // ); 315 | } 316 | else if (this.viewChange[msg.v].length >= 2 * this.f + 1) { 317 | this.registerTimeEvent( 318 | { name: 'skipToNextView', params: { oldView: this.oldView } }, 319 | this.viewChangeTimeout * 1000 320 | ); 321 | } 322 | } 323 | else if (msg.type === 'new-view') { 324 | // do not view change to smaller view 325 | if (msg.v <= this.view) return; 326 | // new primary 327 | if (this.isPrimary && 328 | (msg.v % this.nodeNum) === (parseInt(this.nodeID) - 1)) { 329 | return; 330 | } 331 | // old primary 332 | if (this.isPrimary) { 333 | this.logger.info(['switch to backup node']); 334 | //clearInterval(this.proposeTimer); 335 | this.isPrimary = false; 336 | } 337 | // somehow verify O and V is reasonable 338 | this.logger.info(['enter new view', `${this.view} -> ${msg.v}`]); 339 | this.view = msg.v; 340 | this.isInViewChange = false; 341 | msg.O.forEach(msg => { 342 | // push pre-prepare 343 | this.extendVector2D(this.prePrepare, msg.v, msg.n); 344 | // pre-prepare[v][n] should only have one message 345 | if (this.prePrepare[msg.v][msg.n].length === 0) { 346 | // re-consensus d 347 | if (msg === undefined) { console.log("!! 343"); process.exit(0); } 348 | this.prePrepare[msg.v][msg.n].push(msg); 349 | this.digest[msg.d] = { 350 | isReceived: true, 351 | isPrepared: false, 352 | isDecided: false, 353 | }; 354 | this.registerTimeEvent( 355 | { name: 'executeTimeout', params: { d: msg.d, v: msg.v } }, 356 | this.executeTimeout * 1000 357 | ); 358 | // send prepare 359 | const prepareMsg = { 360 | type: 'prepare', 361 | v: msg.v, 362 | n: msg.n, 363 | d: msg.d, 364 | i: this.nodeID 365 | }; 366 | this.extendVector2D(this.prepare, msg.v, msg.n); 367 | this.prepare[msg.v][msg.n].push(prepareMsg); 368 | // send when other nodes receive new-view 369 | this.send(this.nodeID, 'broadcast', prepareMsg); 370 | } 371 | else { 372 | console.log(`${this.nodeID}, view-change pre-prepare conflict`); 373 | console.log('1', this.prePrepare[msg.v][msg.n][0]); 374 | console.log('2', msg); 375 | this.logger.warning(['view change pre-prepare conflict']); 376 | } 377 | }); 378 | this.hasReceiveRequest = false; 379 | this.registerTimeEvent( 380 | { 381 | name: 'receiveTimeout', 382 | params: { 383 | v: this.view 384 | } 385 | }, 386 | this.receiveTimeout * 1000 387 | ); 388 | if (msg.prePrepareMsg) this.handlePrePrepareMsg(msg.prePrepareMsg); 389 | if (msg.prepareMsg) this.handlePrepareMsg(msg.prepareMsg); 390 | } 391 | else { 392 | this.logger.warning(['undefined msg type']); 393 | } 394 | } 395 | 396 | onTimeEvent(timeEvent) { 397 | super.onTimeEvent(timeEvent); 398 | const functionMeta = timeEvent.functionMeta; 399 | switch (functionMeta.name) { 400 | case 'start': 401 | this.start(); 402 | break; 403 | case 'issueRequest': 404 | if (this.isPrimary) { 405 | this.issueRequest(); 406 | } 407 | break; 408 | case 'receiveTimeout': 409 | if (this.hasReceiveRequest) { 410 | this.hasReceiveRequest = false; 411 | this.registerTimeEvent( 412 | { 413 | name: 'receiveTimeout', 414 | params: { 415 | v: this.view 416 | } 417 | }, 418 | this.receiveTimeout * 1000 419 | ); 420 | } 421 | else if (!this.isInViewChange && this.view === functionMeta.params.v) { 422 | this.logger.info(['did not receive any request']); 423 | this.startViewChange(this.view + 1); 424 | } 425 | break; 426 | case 'executeTimeout': 427 | if (!this.digest[functionMeta.params.d].isDecided && 428 | !this.isInViewChange && functionMeta.params.v === this.view) { 429 | this.logger.info([timeEvent.triggeredTime, 'not executed in time', functionMeta.params.d]); 430 | this.startViewChange(this.view + 1); 431 | } 432 | break; 433 | case 'broadcastNewViewPrepare': 434 | this.newViewPrepareMsgs.forEach( 435 | msg => this.send(this.nodeID, 'broadcast', msg) 436 | ); 437 | break; 438 | case 'skipToNextView': 439 | if (functionMeta.params.oldView !== this.view) { 440 | this.skipToNextView(functionMeta.params.oldView); 441 | } 442 | break; 443 | default: 444 | console.log('undefined function name'); 445 | process.exit(0); 446 | } 447 | } 448 | 449 | // if the next primary is also dead 450 | skipToNextView(oldView) { 451 | if (this.view === this.oldView) { 452 | this.logger.info(['skip to next view']); 453 | const view = this.viewChangeMsg.v; 454 | this.viewChangeMsg.v = view + 1; 455 | this.extendVector(this.viewChange, view + 1); 456 | const tvc = JSON.parse(JSON.stringify(this.viewChangeMsg)); 457 | this.viewChange[view + 1].push(tvc); 458 | this.send(this.nodeID, 'broadcast', tvc); 459 | this.viewChangeTimeout *= 2; 460 | this.executeTimeout *= 2; 461 | this.receiveTimeout *= 2; 462 | this.logger.info([`doubling timeout ${this.viewChangeTimeout} ${this.executeTimeout} ${this.receiveTimeout}`]); 463 | 464 | this.registerTimeEvent( 465 | { name: 'skipToNextView', params: { oldView: oldView } }, 466 | this.viewChangeTimeout * 1000 467 | ); 468 | } 469 | } 470 | 471 | startViewChange(nextView) { 472 | this.logger.info([`start a view change to ${nextView}`]); 473 | this.isInViewChange = true; 474 | 475 | const p = (this.prePrepare[this.view] === undefined) ? [] : 476 | this.prePrepare[this.view] 477 | .slice(this.lastStableCheckpoint + 1) 478 | .filter(msgArray => { 479 | if (msgArray.length === 0) { 480 | return false; 481 | } 482 | return this.digest[msgArray[0].d].isPrepared; 483 | }) 484 | .map((msgArray) => { 485 | const msg = msgArray[0]; 486 | return { 487 | 'pre-prepare': msg, 488 | prepare: this.prepare[msg.v][msg.n] 489 | .filter(_msg => _msg.d === msg.d) 490 | }; 491 | }); 492 | this.viewChangeMsg = { 493 | type: 'view-change', 494 | v: nextView, 495 | n: this.lastStableCheckpoint, 496 | C: (this.lastStableCheckpoint <= 0) ? [] : 497 | this.checkpoint[this.lastStableCheckpoint] 498 | .groupBy(msg => msg.d) 499 | .maxBy(pair => pair[1].length)[1], 500 | P: p, 501 | i: this.nodeID 502 | }; 503 | this.extendVector(this.viewChange, nextView); 504 | const tvc = JSON.parse(JSON.stringify(this.viewChangeMsg)); 505 | this.viewChange[nextView].push(tvc); 506 | this.send(this.nodeID, 'broadcast', tvc); 507 | this.oldView = this.view; 508 | 509 | this.viewChangeTimeout *= 2; 510 | this.executeTimeout *= 2; 511 | this.receiveTimeout *= 2; 512 | this.logger.info([`doubling timeout view change timeout: ${this.viewChangeTimeout}, execute timeout: ${this.executeTimeout}, receive timeout: ${this.receiveTimeout}`]); 513 | } 514 | 515 | genRequest() { 516 | const request = uuid(); 517 | this.digest[request] = { 518 | isReceived: true, 519 | isPrepared: false, 520 | isDecided: false, 521 | }; 522 | const prePrepareMsg = { 523 | type: 'pre-prepare', 524 | v: this.view, 525 | n: this.seq, 526 | d: request, 527 | i: this.nodeID 528 | }; 529 | this.extendVector2D(this.prePrepare, this.view, this.seq); 530 | this.prePrepare[this.view][this.seq].push(prePrepareMsg); 531 | 532 | const prepareMsg = { 533 | type: 'prepare', 534 | v: this.view, 535 | n: this.seq, 536 | d: request, 537 | i: this.nodeID 538 | }; 539 | this.extendVector2D(this.prepare, this.view, this.seq); 540 | this.prepare[this.view][this.seq].push(prepareMsg); 541 | this.seq++; 542 | 543 | return [prePrepareMsg, prepareMsg]; 544 | } 545 | 546 | issueRequest() { 547 | const [prePrepareMsg, prepareMsg] = this.genRequest(); 548 | this.send(this.nodeID, 'broadcast', prePrepareMsg); 549 | // BUG! Leader doesn't need to broadcast prepare message 550 | this.send(this.nodeID, 'broadcast', prepareMsg); 551 | } 552 | 553 | start() { 554 | if (this.isPrimary) { 555 | this.issueRequest(); 556 | } 557 | else { 558 | this.registerTimeEvent( 559 | { 560 | name: 'receiveTimeout', 561 | params: { 562 | v: this.view 563 | } 564 | }, 565 | this.receiveTimeout * 1000 566 | ); 567 | } 568 | 569 | } 570 | 571 | constructor(nodeID, nodeNum, network, registerTimeEvent) { 572 | super(nodeID, nodeNum, network, registerTimeEvent); 573 | this.f = Math.floor((this.nodeNum - 1) / 3); 574 | // pbft 575 | this.view = 0; 576 | this.isPrimary = 577 | (this.view % this.nodeNum) === (parseInt(this.nodeID) - 1); 578 | this.checkpointPeriod = 3; 579 | this.seq = 0; 580 | this.isInViewChange = false; 581 | this.proposePeriod = 2; 582 | this.lastDecidedSeq = -1; 583 | this.lastDecidedRequest = ''; 584 | this.isDecided = false; 585 | // view change 586 | // check if a node receive a request in time 587 | this.lambda = config.lambda; 588 | this.receiveTimeout = 3 * this.lambda; 589 | this.hasReceiveRequest = false; 590 | this.executeTimeout = 3 * this.lambda; 591 | this.viewChangeTimeout = 2 * this.lambda; 592 | // this makes nodes create checkpoint at n = 0 593 | this.lastStableCheckpoint = 0; 594 | // log 595 | this.digest = {}; 596 | this.prePrepare = []; 597 | this.prepare = []; 598 | this.commit = []; 599 | this.checkpoint = []; 600 | this.viewChange = []; 601 | this.registerTimeEvent({ name: 'start', params: {} }, 0); 602 | } 603 | } 604 | 605 | module.exports = PBFTNode; 606 | --------------------------------------------------------------------------------