btcsuite / btcd

An alternative full node bitcoin implementation written in Go (golang)
https://github.com/btcsuite/btcd/blob/master/README.md
ISC License
6.23k stars 2.36k forks source link

Difficulty adjustment questions #727

Closed cpacia closed 8 years ago

cpacia commented 8 years ago

Hi, I'm working on an spv wallet which uses some code from btc and I'm running into some issues. I'm using your difficulty adjust algorithm as a reference and it looks to me like your grabbing the starting timestamp from the 2016th previous block (unless I'm just reading that wrong, but it looks like it's lastNode plus 2015 previous nodes = 2016, right?): https://github.com/btcsuite/btcd/blob/491acd4ca6f88d18afdb0294e3899257140c0df0/blockchain/difficulty.go#L301

The bitcoin.org developer guide says to use the timestamp from the 2015th previous block because of bug in the Core that never got fixed. If I used 2016 blocks like you have here, the mainnet chain syncs fine for me, but the testnet chain does not. If I used 2015 blocks the mainnet chain doesn't sync while the testnet chain does.

Anyway, I'd appreciate it if you could point me in the right direction.

Also, unrelated, I was always under the impression that miners were permitted to set difficulty target in the bits field lower than the actual required target. That is, if they want to voluntarily do more work, they can. Of course it doesn't make any sense for a miner to do that, but I see your difficulty adjustment code takes the bits from the previous block and uses it as current difficult target when retargeting: https://github.com/btcsuite/btcd/blob/491acd4ca6f88d18afdb0294e3899257140c0df0/blockchain/difficulty.go#L333

If I'm right about the rule allowing lower difficulty in the bits field, then it's possible your code fail to calculate the correct difficulty if a miner sets a lower difficulty target on the block before an adjustment.

cpacia commented 8 years ago

I'm looking at bitcoin Core and it looks like it's the same as your code. So I've just confused myself apparently.

cpacia commented 8 years ago

I'm going to close this because it this code looks identical to core. And so does mine for that matter, not sure why I can't sync the testnet.

bazarijoo commented 6 years ago

Hello. You mentioned that changing the whole difficulty(target) does not happen by changing the bits field alone. Do know what should be changed in the bit coin source code to change the whole difficulty and make the main network run properly ?