From 3bcb0426c3e021c86856f3e71cdd76992a824973 Mon Sep 17 00:00:00 2001 From: Patrick Nagurny Date: Fri, 4 Sep 2015 13:52:54 -0400 Subject: [PATCH] get block reward --- lib/blocks.js | 17 ++++++++++++++++- test/blocks.js | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/blocks.js b/lib/blocks.js index 7b862ae..30892e7 100644 --- a/lib/blocks.js +++ b/lib/blocks.js @@ -4,6 +4,7 @@ var common = require('./common'); var async = require('async'); var bitcore = require('bitcore'); var BufferUtil = bitcore.util.buffer; +var BN = bitcore.crypto.BN; function BlockController(node) { this.node = node; @@ -52,7 +53,7 @@ BlockController.prototype.transformBlock = function(block, info) { chainwork: info.chainWork, previousblockhash: blockObj.header.prevHash, nextblockhash: null, // placeholder - reward: 0, // First output of first transaction gives us the reward + fees. How to isolate just reward? + reward: this.getBlockReward(info.height) / 1e8, isMainChain: true // placeholder } }; @@ -125,4 +126,18 @@ BlockController.prototype.list = function(req, res) { }); }; +BlockController.prototype.getBlockReward = function(height) { + var halvings = Math.floor(height / 210000); + // Force block reward to zero when right shift is undefined. + if (halvings >= 64) { + return 0; + } + + // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years. + var subsidy = new BN(50 * 1e8); + subsidy = subsidy.shrn(halvings); + + return parseInt(subsidy.toString(10)); +}; + module.exports = BlockController; \ No newline at end of file diff --git a/test/blocks.js b/test/blocks.js index 07ef4e3..77520f8 100644 --- a/test/blocks.js +++ b/test/blocks.js @@ -200,4 +200,20 @@ describe('Blocks', function() { blocks.blockIndex(req, res, next, height); }); }); + + describe('#getBlockReward', function() { + var blocks = new BlockController({}); + + it('should give a block reward of 50 * 1e8 for block before first halvening', function() { + blocks.getBlockReward(100000).should.equal(50 * 1e8); + }); + + it('should give a block reward of 25 * 1e8 for block between first and second halvenings', function() { + blocks.getBlockReward(373011).should.equal(25 * 1e8); + }); + + it('should give a block reward of 12.5 * 1e8 for block between second and third halvenings', function() { + blocks.getBlockReward(500000).should.equal(12.5 * 1e8); + }); + }); }); \ No newline at end of file