From cadbc0a79d1219ea8daee3770f285a859b4ada39 Mon Sep 17 00:00:00 2001 From: Braydon Fuller Date: Wed, 16 Sep 2015 09:23:13 -0400 Subject: [PATCH] GetBlockIndex segmentation fault with genesis block Fixes an bug where accessing `prevBlockIndex->phashBlock` for the genesis block would cause a segmentation fault with an error of "Cannot access memory at address 0x0". As the genesis block doesn't have a previous hash, it will now set the "prevHash" to "null". --- integration/regtest.js | 5 +++++ src/libbitcoind.cc | 12 +++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/integration/regtest.js b/integration/regtest.js index bf5c7ac5..0675bf52 100644 --- a/integration/regtest.js +++ b/integration/regtest.js @@ -231,6 +231,11 @@ describe('Daemon Binding Functionality', function() { blockIndex.height.should.equal(i + 1); }); }); + it('will get null prevHash for the genesis block', function() { + var blockIndex = bitcoind.getBlockIndex(0); + should.exist(blockIndex); + should.equal(blockIndex.prevHash, null); + }); }); describe('get block index by height', function() { diff --git a/src/libbitcoind.cc b/src/libbitcoind.cc index 0c3b8758..bb3ed015 100644 --- a/src/libbitcoind.cc +++ b/src/libbitcoind.cc @@ -1337,14 +1337,20 @@ NAN_METHOD(GetBlockIndex) { } } + Local obj = NanNew(); + arith_uint256 cw = blockIndex->nChainWork; CBlockIndex* prevBlockIndex = blockIndex->pprev; - const uint256* prevHash = prevBlockIndex->phashBlock; + if (&prevBlockIndex->phashBlock != 0) { + const uint256* prevHash = prevBlockIndex->phashBlock; + obj->Set(NanNew("prevHash"), NanNew(prevHash->GetHex())); + } else { + obj->Set(NanNew("prevHash"), NanNull()); + } - Local obj = NanNew(); obj->Set(NanNew("hash"), NanNew(blockIndex->phashBlock->GetHex())); obj->Set(NanNew("chainWork"), NanNew(cw.GetHex())); - obj->Set(NanNew("prevHash"), NanNew(prevHash->GetHex())); + obj->Set(NanNew("height"), NanNew(blockIndex->nHeight)); NanReturnValue(obj);