Skip to content
This repository has been archived by the owner on Aug 16, 2021. It is now read-only.

Longest chain timeout #229

Closed
dangershony opened this issue Jul 13, 2017 · 22 comments
Closed

Longest chain timeout #229

dangershony opened this issue Jul 13, 2017 · 22 comments

Comments

@dangershony
Copy link
Contributor

When a peer that connected with a longer chain got disconnected before our node downloaded the blocks we need to disconnect and reset the longest chain to one of the connected peers

@dangershony
Copy link
Contributor Author

@Aprogiena
Copy link
Contributor

This issue applies to both - Bitcoin and Stratis,

but in case of Stratis, there seems to be an attack scenario for POS where one is able to assemble a chain of block headers (but not blocks!) and present them as a longer chain, the node will probably try to get that chain, which will result in either the peer providing invalid block (he does not have those blocks), or he will refuse to provide them (won't reply). What we need to do here is that we make sure such node is disconnected (immediately [and banned] if provided invalid block; or after some timeout if it does not respond) and then we need to resolve as @dangershony mentioned above - we need to reset our longest chain to the best chain of currently connected peers (and make sure to handle a situation where we don't have any connected peers when that happens, so switch to the best chain of any new peer that connects later).

@bokobza
Copy link
Contributor

bokobza commented Nov 3, 2017

@Aprogiena
Copy link
Contributor

So what was the approach we wanted to take here? Have we agreed on this going to ChainHeadersBehavior at the end or not?

@Aprogiena
Copy link
Contributor

I've forgotten the resolution, but I can remember now that we've mentioned that we need to access all nodes, which is not easy to do in CHB. I think I've suggested putting list of nodes into ChainState. But don't know if we made further progress on the discussion and resolved it somehow.

So what is the design here?

@dangershony
Copy link
Contributor Author

We need to first identify if this is a consensus problem or node problem, and also how to approach the fix:

  1. on disconnect, default to the next longest chain form one of the peers.
  2. when asking for a block and the block does not arrive or its invalid.
    There is much more complexity with option 2.

This is probably a node problem (and not only consensus) while its easier to determine false headers when we have a consensus mechanism in place, this issue can also effect nodes that are not running the consensus verification code. (a light wallet that was given a fake longer chain will not swap back to the correct chain until its longer, or until the blocks are asked).

In my view the approach to fix this would be on a disconnect of a peer the following should happen.

  • check if the disconnected peer is beyond checkpoint/assume-valid.
  • check if the peer is the same as chain.Tip
  • if yes compare tip to all other connected peers to check if it was the only that was longer
  • if yes and consensus tip (chainState.ConsensusTip ) is behind role back chain.Tip to chainState.ConsensusTip or the longest peer.

@mikedennis
Copy link
Contributor

Thanks guys. This is all new code for me so apologize in the advance for dumb questions 😀
After a quick initial look I see one of two potential approaches:

  1. Do disconnect logic in ChainHeaderBehavior. As Apro mentioned it looks like CHB is lacking access to the other peers so we could add access to peers via ChainState and then do the disconnect logic here: https://github.com/stratisproject/StratisBitcoinFullNode/blob/master/src/Stratis.Bitcoin/Base/ChainHeadersBehavior.cs#L309-#L316

  2. Or perhaps we could do the disconnect logic in Connection Manager: https://github.com/stratisproject/StratisBitcoinFullNode/blob/master/src/Stratis.Bitcoin/Connection/ConnectionManager.cs#L311-#L318
    We could add an ShouldRollback property to CHB that does has the logic of the last condition of your list and access it via
    ChainHeadersBehavior chainHeadersBehavior = node.Behavior<ChainHeadersBehavior>();

I'm leaning towards 2. Seems more like a connection manager issue than a behavior issue. What do you guys think?

@Aprogiena
Copy link
Contributor

Aprogiena commented Nov 19, 2017

@dangershony explain

check if the disconnected peer is beyond checkpoint/assume-valid.

afaik CP/AV is on higher level, not on headers level, so what do you want to achieve with this check?

@Aprogiena
Copy link
Contributor

@mikedennis

  1. DetachCore might be better, or not?
  2. not sure, i'm not familiar with CM

@dangershony
Copy link
Contributor Author

afaik CP/AV is on higher level, not on headers level

Why not? assume valid has a block id thats all we need to identify a header is not part of the main chain.

@Aprogiena
Copy link
Contributor

if you have AV or CP at height X with hash h(X)
and you are now working with peer that disconnected and its chain was longest at its height was X-1000
then you don't know if that AV/CP block with hash h(X) is on the chain if you only have headers up to h(X-1000)

so what i'm saying is that i can't see what you want to check or how does that check helps in that scenario

what could help you is that if the peer has tip at height X+100, and the next best peer has X-100, then of course if you know you want chain with X, you don't need to go back to X-100, just X, but that's different scenario and maybe not even worth considering

@noescape00
Copy link
Contributor

noescape00 commented Feb 26, 2018

I think we can do it like this (mostly based on @dangershony's proposal):

In ConnectionManager on the peer removal we can check if we have any peers that are as advanced as the removed one. If we do- we're fine and finish here because LookaheadBlockPuller will reassign the download task to some other peer.
Otherwise find the most advanced peer and check if it's chain is ahead of our block store tip. If it does- switch to his chain. Otherwise just rewind to the consensus tip.

And on top of that change the BlockPuller.OnStalling().
Now if the peer doesn't provide blocks that were assigned to it in a reasonable time we release all the download tasks and reassigning them to other peers basing on the quality score (it's actually random, but weighted with the quality score). The problem is if there is just 1 peer that has the chain long enough the download task will be assigned to it no matter the quality score.
I suggest that before releasing the download jobs we check if there is any peer with chain long enough to reassign the download to AND not minimal quality score. If not- wait some more just in case it's a really slow peer and disconnect from it if it still can't provide anything. If there is- reassign the job to with non-minimal quality score- just release the download tasks.
This will ensure having a timeout on a chain if the peer (or peers) that announced the best chain doesn't provide any blocks.

Let me know what you think about it. If all are fine with the suggested solution I'll proceed to implementing this.

@Aprogiena
Copy link
Contributor

First of all, I think block puller behaviour should inform the block puller to remove the assignments for its peer when it's disconnected.

This is important because otherwise we would wait for not connected peer to deliver something. I can't remember if we have any mechanism in place for this situation, but I wouldn't expect that we have.

Note that we will refactor connection manager and therefore it is hard to design anything with connection management at this point, we should first do the refactoring and then come back to this issue.

There is issue in the GitHub already for that problem with one peer, it should not be mixed with this issue.

I think we need to discuss this more but not before the big refactoring because it doesn't make sense until that. There's also another issue that I will be talking about tomorrow that should be discussed before we start implementing anything here.

So regular notice – please do not start with implementation

@noescape00
Copy link
Contributor

First of all, I think block puller behaviour should inform the block puller to remove the assignments for its peer when it's disconnected.
This is important because otherwise we would wait for not connected peer to deliver something. I can't remember if we have any mechanism in place for this situation, but I wouldn't expect that we have.

Yeah, we're already doing that- BlockPullerBehavior calls ReleaseAllPeerDownloadTaskAssignments on detach core.

Note that we will refactor connection manager and therefore it is hard to design anything with connection management at this point, we should first do the refactoring and then come back to this issue.

Ok, reasonable. Let's first do the #1090

@Aprogiena
Copy link
Contributor

Oh, do we? Silly me then, my expectation was worse than reality

@dangershony
Copy link
Contributor Author

Ok bring this back to live I think we definitely need to implement such a behaviour, this will also help a bit with the headerx problem (but not solve it obviously)

Consider this behaviour to only live in the Consensus feature
When a peer gets disconnected we check

  • Peer.Tip if it within the same chain as our Headers.Tip
  • No other peer is on that same chain
  • Consensus.Tip is behind (here we could potentially check if the fork is inside Consensus.Tip (the trusted base like you call it) then we could assume we are ok)

If all above conditions are met jump to the next best Header.Tip

The puller needs to potentially also get involved perhaps if we get a timeout form a peer on receiving a block we disconnect and ban it (or we keep a counter and ban it after x failed timeouts) then on disconnect the behaviour will get triggered and if the node has provided us with bad headers we will swap to a better node.

If we only have once connection then we ofcourse do nothing.

@Aprogiena
Copy link
Contributor

On Skype we have mentioned that we would like to separate switching of the best chain from disconnected peer and some kind of timeout. So the very 1st PR here should only deal with the switch of the chain when a peer disconnects.

@Aprogiena
Copy link
Contributor

If we only have once connection then we ofcourse do nothing.

I would say that if we have only one connection and it gets disconnected, then we switch headers tip to consensus tip

@Aprogiena
Copy link
Contributor

The timeout part should probably be solved after header X together with miner block data withdrawal Issue

@dangershony
Copy link
Contributor Author

then we switch headers tip to consensus tip

Yeah sounds correct to me

Yes as we discussed this can be two separate PRs 1. switch on disconnect 2. disconnect on timeout.

@Aprogiena
Copy link
Contributor

We are now working on this issue, basic idea is clear and we all agree on that, but the concrete implementation may differ little bit, but hopefully that is okay.

@noescape00
Copy link
Contributor

already fixed on master

codingupastorm pushed a commit to codingupastorm/StratisBitcoinFullNode that referenced this issue Feb 24, 2019
dangershony added a commit that referenced this issue Mar 13, 2019
* Change to tag counter chain transaction with sessionId
Imported from Changeset 152

* Moved Payload into feature
Imported from Changeset 154

* Added address validation to CrossChainTransactionMonitor
Imported from Changeset 155

* Refactoring
Imported from Changeset 156

* Changed op_return to byte[] on counter chain
Imported from Changeset 157

* Removed Add for CounterChainTransactionId 
Imported from Changeset 159

* Refactored SessionManager into two session managers, one for each chain.
Imported from Changeset 160

* Added new Session managers
Imported from Changeset 161

* Added new session managers to the feature services.
Imported from Changeset 162

* Updated monitor to use new session manager.
Imported from Changeset 163

* Removed PartialTransactionSessionManager from Monitor
Imported from Changeset 164

* Removed old session manager from feature
Imported from Changeset 165

* Removed old session manager from Behavior
Imported from Changeset 166

* updated behavior
Imported from Changeset 167

* session updated in feature
Imported from Changeset 168

* Removed PartialTransactionSessionManager
Imported from Changeset 169

* Added file PartialTransactionSession.cs
Imported from Changeset 170

* Refactoring MonitorChainSessionManager
Imported from Changeset 171

* Refactored BuildAndBroadcastSession into MonitorChainSession
Imported from Changeset 172

* Refactor MonitorChainSession
Imported from Changeset 173

* Refactored controller
Imported from Changeset 174

* Refactoring of RunSessionAsyc
Imported from Changeset 175

* refactor of sessions
Imported from Changeset 176

* added checking for ProcessChainSession
Imported from Changeset 177

* Rollback latest changes
Imported from Changeset 178

* Added shutdown check before trying to broadcast a transaction.
Imported from Changeset 179

* Added shutdown check before trying to broadcast a transaction.
Imported from Changeset 180

* refactored RunSessionAsync
Imported from Changeset 181

* refactored RunSessionAsync
Imported from Changeset 182

* refactored RunSessionAsync
Imported from Changeset 183

* refactored RunSessionAsync
Imported from Changeset 184

* Removed hard coded federation M and N values.
Imported from Changeset 187

* Refactor VerifySession method in CounterChainSessionManager.
Imported from Changeset 188

* Refactor VerifySession method in CounterChainSessionManager.
Imported from Changeset 189

* Removed hardcoded multisig wallet name and move to config and FederationGatewaySettings.
Imported from Changeset 194

* Added comments to the CounterChainSessionManager.
Imported from Changeset 196

* Added comments to several files.
Imported from Changeset 197

* Attempt to merge Enigma and EnigmaChain
Imported from Changeset 201

* Updated the solution with the latest Stratis.Bitcoin nuget packages
Imported from Changeset 202

* Removed the custom encryption algos

* Remove custom env mockup helpers (#5)

* created Apex definition

* first bit of cleaning, all the mockup helpers have been removed as no special logic is needed to handle sidechains, they are just another network. Need to add back randomised API port attribution. Need to fix getCoinDetails test if it is being used by anyone (UI ?). The powershell command projects have been removed as they were only here to generate json files that have disappeared.

* delete unused projects

* Bring back FindPorts methods to later find a way to use it

* Fix to get different API ports when creating multiple connected nodes on localhost, fix to GetCoinDetails, a bit basic for the moment, but we'll see how the code evolved

* Put explanatory name on the Class in FederatedSidechains.Tests.Common

* this doesn't work, somehow the constructor is called twice, and once with a null nodesettings, I need to investigate

* Changes after PR comments

* more merge changes ...

* fix get-coindetails logic

* Removed placeholder project and wrongly copied MainchainGeneratorService

* consolidate .Net Sdk

* Jeremy's PR 14 reproduced with pr5 changes in (#15)

* upgrade nuget 1.1.7 to 1.1.9 and 4.0.0.57 and 4.0.0.58

* add NLog

* Add new network properties to Apex

* Update ApexNetwork.cs

* Update ApexNetwork.cs

* Remove some tests (#17)

* Removed some tests
Removed tests about coin details as this will a property of the Network object.
Removed tests about premining as this should be in the FN
Removed those checking that nodebuilder can start a node properly

* use findPorts from Stratis.Bitcoin.IntegrationTestsCommon

* Removed some tests that exist in FN
Adapted blockChaingeneration

* added back correctly_identify_sidechain

* tidied up references (#18)

All good

* Gateway deamons and GatewaySettings changes (#20)

* upgrade nuget 1.1.7 to 1.1.9 and 4.0.0.57 and 4.0.0.58

* add NLog

* added CoinbaseMaturity, PremineReward, pow reward, pos reward and max reorg for the apex network.

* Add new network properties to Apex

* Update ApexNetwork.cs

* Update ApexNetwork.cs

* improve the way we start gateways up

* Changes to FederationGatewaySettings
the aim is to simplify the config file and try to derive most settings directly from the redeem script

* Parse IP addresses in the GatewaySettings
Have 2 logics for gateway node builder

* Nuget update (#21)

* updated nuget packages

* Replced ApiPort by GetApiPort from the FN

* create custom node without asking for free api

* added maxMoney and coinTicker

* Networkz (#22)

* using Apex throughout solution

* removed unused assert method in Networks

* remove left behind

* remove extra space

* Update GPW with mnemonic and HD multisig capability (#7)

* Add nodes (#23)

* Remove special nuget location

* added membername to config

* added mainchain to launchSettings

* Added addnode for federation ips

* returned null if there are no fed ips

* added import-key endpoint (#24)

* Multisig wallet (#26)

* Removed classes and interfaces that can be from the wallet feature

* remove some unused controller methods

* ChainCode and Multisig HD operations

* made accounts non-hd

* Move the import key to the GPW

* integrated the multisig wallet to the federation feature

* Included Federation multisig tests

* merge2

* updated settings

* split wallet object

* wallet check before save (#28)

* Wallet check (#29)

* wallet check before save

* Excluded trxs that are coinbase and with value 0
added scriptpubkey to the wallet creation

* now creating the wallet file when the node is started the first time, no need to waut for the user's mnemonic (#30)

* Remove FederationFolder logic and use FederationGatewaySettings instead (#31)

* upgrade nuget 1.1.7 to 1.1.9 and 4.0.0.57 and 4.0.0.58

* add NLog

* added CoinbaseMaturity, PremineReward, pow reward, pos reward and max reorg for the apex network.

* Add new network properties to Apex

* Update ApexNetwork.cs

* Update ApexNetwork.cs

* little code cleanups

* remove the FederationMemberFolder logic, use FederationGatewaySettings instead

* update comment

* remove unused parameters

* Revert "remove unused parameters"

This reverts commit 091504c1821e3050875aeaf681c7dbb3ba9d7e8f.

* remove unused parameters - without unwanted changes this time

* Fix error in boss card passing and block delay checks (#32)

* Added signing of outputs with the private key (#33)

* Logging additions (#34)

* Added signing of outputs with the private key

* Added some logging

* Use correct representation of pubkey (#35)

* Moved the FederatedPeg project into the FederationGateway project (#36)

* WalletReference and AddCoins (#37)

* Moved the FederatedPeg project into the FederationGateway project

* added some logs and removed the WalletReference from the trxBuilder

* Fix AddCoins

* rollbacked launch settings

* fixed the build (#38)

* Federation objects (#39)

* Federation objects

* added the pubkey setting to the .conf files examples

* added GetFull Transaction method (#40)

* MemberName in the logs (#41)

* MemberName is not necessary in the logs
More log changes

* remove membername from the template and integration test too

* Upgrade 1.1.11 to 1.1.12 (#42)

* upgrade nuget 1.1.7 to 1.1.9 and 4.0.0.57 and 4.0.0.58

* add NLog

* added CoinbaseMaturity, PremineReward, pow reward, pos reward and max reorg for the apex network.

* Add new network properties to Apex

* Update ApexNetwork.cs

* Update ApexNetwork.cs

* upgrade nuget packages

* Added default constructor for payload. (#43)

* first suggestion for AddPartial fix (#45)

* first suggestion for AddPartial fix

* simplify counterchainsession.cs and add namespace

* Partial list (#46)

* don't include partial trxes that are already in the list

* Removed unused properties

* Changed some logs

* changed the sessionid in opreturn to be byte[]

* Remove some controller methods used only in the standard wallet:
from controller:
GetTransactionFeeEstimate
BuildTransaction
SendTransaction
From the transaction handler:
FundTransaction
EstimateFee

* fix

* remove string interpolation

* updated nuget packages (#48)

* Small fixes (#49)

* Added a LoadKeysLookup

* Remove the password from the GetExtended call

* check if a Peer is in the federation before registering or sending message to it (#50)

* check if a Peer is in the federation before registering or sending message to it

* don't send message to non federation peers

* Remove hardcoded password and add API call to supply password after node startup (#51)

* Partial transaction for federation members only (#52)

* check if a Peer is in the federation before registering or sending message to it

* don't send message to non federation peers

* hopefully better way to compare ip endpoints

* Added propogation of final destination transactionId back to the monitor chain. (#55)

* handle exceptions in cross-chain calls (#57)

* Deposit (#58)

Deposit Fix

* Minining on Sidechain members (#60)

* Only use the federation members to mine

* Added handling of reorged blocks

* Removed some unnecessary null checks

* Set the federation debug file to Trace by default

* Added the recover cal to the setup Fiddler session

* Improvements (#61)

* Added seednodes to the SidechainD project

* check publickey is part of the multisig

* Removed some files (#62)

* Removed some files

* better error when password is missing

* Added minimum transfer amount constraint. (#63)

* CounterChainTransactionId propogation.  Completed and Tested version. (#64)

* Ensure all nodes get the CounterChainTransactionId (#66)

* first cut, try to remove dependency of bosscard on transaction hash (#68)

* first cut, try to remove dependency of bosscard on transaction hash

* I forgot things in mainchain monitor

* Log BlockHeight in PartialTransactionBehavior

* Sessions (#70)

* Moved the check for MinimumTransferAmount to earlier i nthe process

* sessions with multiple transactions

* added trxes info in RegisterSession

* Remove hash op return

* monitor session only on transactions found

* Fixed VerifySession

* Few minor cleanups, hopefully an easy PR (#71)

* upgrade to dotnetcore 2.1, tests as libraries (#98)

well done mate, that is awesome

* Upgrade to fullnode 1.2.1 beta (#110)

* Upgrade NBitcoin and as little dependencies as possible

* Consolidate Stratis.Bitcoin

* Upgrade all other Stratis and external packages

* Trying to resolve genesis hash discrepancies in Apex

* make sure all projects are in full debug mode, needed for code coverage analysis (#127)

* OpReturnDataReader (#140)

* interface and test opReturnDataReader

* minor refactor, do not accept two op_returns, test for it (#141)

* introduce interface for settings and make them readonly (#142)

* introducing deposit class (#143)

specific method for OpReturnDataReader to be used by deposit extractor

* upgrades libraries (#144)

* upgrades to
Stratis.Bitcoin.* 1.2.3-beta
NStratis 4.0.0.67
Microsoft.NET.Test.Sdk 15.9.0
Xunit 2.4.1

That meant removing unused Integration test project which used corrupted Stratis.Bitcoin.IntegrationTests.Common temporarily

* only extract deposits from blocks that have matured (#147)

* only extract deposits from blocks that have matured

* remove useless constant initially introduced for getordefault

* my bad, I didn't change all the types to use the interface :/ (#149)

* Add Apex NetworkSelector (#148)

* use rest to post new matured blocks because it is easier to understand (#151)

* Leader ordering and change. (#150)

* Initial commit.

Created interface and class implementation for the LeaderProvider.

Added unit test.

Included it in the FederationGatewayFeature and BlockObserver.

* Add new ReceiveCurrentBlockTip end point.

Update LeaderProvider to use BlockTipModel.

* Add BlockTip Model.

Complete receive-current-block-tip end point (ReceiveCurrentBlockTip()).

Add documentation comments.

* Changes after PR review.

Made federated list read only.

Updated test.

* Missing code from branch after previous merge.

* Use uint256 instead of string for block hash.

* Add logic to send on the block tip and hash.

This will logic will assist on who will be the next federated leader.

* Add code analysis rule-set to each project. (#153)

* Removed string parameter from constructor. (#154)

* Removed string parameter from constructor - as it was causing problem constructing the related classes at start-up.

* Make publicationUri local to the method.

* Cast to the right type before calling SendAsync().

I am merging it because I want to get the changes on my PR :) thanks !

* Deterministic creation of target transactions (#155)

* Deterministic creation of target transactions

* Specification updates

* Spec updates 2

* introducing withdrawals (from multisig to target addresses) (#152)

* introducing withdrawals (from multisig to target addresses)
these will be used to track the status of transfers from the target chain point of view

* tests for OpReturnDataReader extraction of transaction ids

* Wrap HttpClient for testing

* Better way to mock HttpClient usage

* fix lack of explicit JsonConverters in places, test matured block sender using Igor's suggestion

* fix typo, thanks @zeptin

* Use cref for types mentioned in the documentation.

* Removed not used 'usings'.

* For Ferdeen

* Minor typo's and spacing.

* just to trigger builds again

* Merge from master to get Gutav's changes

* Rename restMaturedBlockSenderTests.cs to RestMaturedBlockSenderTests.cs (#157)

* Template transaction database (#118)

* Add store class with stub template class

* Remove tests for now

* Remove extra trace logs

* Cross chain transfers statuses suggestion (#159)

* minor fixes from previous PR

* a suggestion for various possible cross chain transfer statuses

* Cross Chain Transfer Store (#161)

* Cross Chain Transfer Store

* Respect -mainchain / -sidechain argument

* Refactor

* Implement RecordLatestMatureDeposits method

* Implement MergeTransactionSignaturesAsync

* Refactor

* Fix xml documentation

* Add Guard

* Update DeleteAsync

* Add mainchain argument to test case

* Add GetTransactionsToBroadcastAsync

* Add comment

* Implement SetRejectedStatus

* Fix InitializeAsync

* Move ExtractDepositsFromBlock into IDepositExtractor and Resync matured block deposits. (#160)

* Move ExtractDepositsFromBlock into it's own interface.  This will then allow me to complete Issue #158 - Resync matured block deposits.

Also moved up FederationGatewayRouteEndPoints into it's own class.

Set FX Cop Non rule-set against Stratis.FederatedPeg.Tests.csproj.

* Moved ExtractMaturedBlockDeposits() into IDepositExtractor.

Removed IMaturedBlockDepositsProcessor.

Updated tests.

* Include logic to send missing matured block deposits.

* Add MinimumDepositConfirmations validation in ResyncMaturedBlockDeposits.

* Add FederationGatewayControllerTests unit tests for ResyncMaturedBlockDeposits() and ReceiveCurrentBlockTip().

* CrossChainTransferStore sets up a DepositExtractor, which now includes IFullNode at construction.

* we can't use services.AddHttpClient from Microsoft.Extensions.Http as it conflicts with the FullNode Api (#163)

* fix the serialisation of the hash, add test (#164)

* Test for RestBlockTipSender(). (#162)

* Test for RestBlockTipSender().

* Move PrepareWorkingHttpClient() and PrepareFailingHttpClient() into a shared class.

Add SendBlockTip_Should_Log_Error_When_Failing_To_Send_IBlockTipAsync() to RestBlockTipSenderTests.

* Adds the SynchronizeAsync method and a test case (#165)

* Adds the SynchronizeAsync method and a test case

* Refactor

* Fix return status

* Changes based on feedback

* Changes based on feedback 2

* Changes based on feedback 3

* Changes based on feedback 4

* Refactor test folder

* Add test case (#166)

* Fix readme try better coverage (#169)

readme.md didn't link to the actual builds
add a runsettings for more precise code coverage metrics

* Add sanity check to sync between store and wallet (#167)

* Refactor TransactionBuilderTest

* Add sanity check

* Fix TransactionBuilderTest

* Fix DataDir

* Refector test

* Mock settings

* Re-use sanity check

* Withdrawal extractor tests (#168)

* finally  Withdrawal extractor tests :/

* A better logic to check transaction for withdrawal

* wire WithdrawalExtractor in and mini refactor

* Just cosmetics (#170)

* remove unused reference from FederatedPeg.Tests

* Interface CrossChainTransfer

* Add StoringDepositWhenWalletBalanceSufficientSucceeds test and refactor (#172)

* Add StoringDepositWhenWalletBalanceSufficientSucceeds test and refactor

* Dummy change

* Fix dummy change

* Events persister (#171)

* remove unused reference from FederatedPeg.Tests

* Interface CrossChainTransfer

* adding event persister class

* EventsPersister tests and fix merge

* Cleanup after tests !

* Event persist withdrawals (#175)

* remove unused reference from FederatedPeg.Tests

* Interface CrossChainTransfer

* adding event persister class

* EventsPersister tests and fix merge

* Cleanup after tests !

* withdrawals extraction and reception

* Refactor store to chase wallet tip (#176)

* Refactor store to chase wallet tip

* Update test cases

* Remove redundant SyunchronizeAsync calls

* Refactor test

* Merge and expand tests

* Add StoreMErgeesSignaturesAsExpected test case

* Event persist withdrawals (#177)

* remove unused reference from FederatedPeg.Tests

* Interface CrossChainTransfer

* adding event persister class

* EventsPersister tests and fix merge

* Cleanup after tests !

* withdrawals extraction and reception

* remove extract withdrawal side effect + test refactor

* unused ref

* put ExtractWithdrawalFromTransaction private again

* remove some code from alpha version (#179)

* Finialize CrossChainStore initial test cases and refactoring (#180)

* Finialize CrossChainStore initial test cases and refactoring

* Code reorg/refactoring and commenting

* Update spending details after signature merge

* Refactor

* Remove DepositPresent

* Add MinCoinMaturity

* Improve fault tolerance

* Remove unused DepositBlockHeight

* Fault tolerance improvements

* Add StoreRecoversFromChain test

* Fix WithdrawalExtractor

* Add comments plus saving of wallet

* Extend test case to verify signature / transaction

* Refactor signature checking

* Cleanup

* Extend StoreRecoversFromChain test

* Comment out WithDrawalsExtactor tests until issue 124 addressed

* Performance optimisation

* Add remarks

* Improve fault tolerance

* Improve fault tolerance

* Refactor multiple methods to GetTransactionByStatusAsync

* Refactor AppendBlock

* Add sorting to GetTransactionsByStatusAsync

* Fix comments

* Update comment

* Refactor IsValid

* Changes based on feedback

* Improve store integrity.

* Refactor test funding

* Implement minimum transaction fee and coin maturity

* Minor changes

* Changes based on feedback

* Changes based on feedback

* Changes based on feedback

* upgrade stratis packages to 1.2.4 and FluentAssertions to 5.5.3 (#181)

* Add `Suspended` status to store (#185)

* Add `Suspended` status to store

* Add the ability to undo the ProcessTransaction operation

* Optimize RecordLatestMatureDepositsAsync and add RemoveTransaction to rollback

* Update RemoveTransaction method

* Call RemoveTransaction when setting Rejected status

* Add StoringDepositsWhenWalletBalanceInSufficientSucceedsWithSuspendStatus test case

* Extend test case and implemt fix

* Implement PartialTransactionRequester (#186)

* Return transaction from MergeTransactionSignatureAsync

* Refactor RequestPartialTransactionPayload

* Refactor PartialTransactionBehaviour

* Add PartialTransactionRequester class

* Add the new class to FederationGatewayFeature

* Changes based on feedback

* Add test StoredPartialTransactionsTriggerSignatureRequests

* Ensure that the transactions being merged share the same template

* Adding a POA federated peg network (#182)

* Adding a POA federated peg network
Currently no smart contract packages so I have commented out the SC specifics ...

* trying to get rid of Apex references

* refactor network selector usaage
I don't think we need 2 classes for that

* no more need to instantiate a network to get its name

* changes post review

* Change Magic, Cointype and targetSpacingSeconds

* add a "test" to run the different tools from within VisualStudio (#187)

* add a "test" to run the different tools from within VisualStudio

* Clear white spaces.

* Signed multisig transaction broadcaster. (#183)

* Initial commit.

New LeaderProvider to stream leader provider changes.

SignedMultisigTransactionBroadcaster component.

* Logic to check mempool and send transaction from CrossChainTransfer store.

* Add ILeaderReceiver & ISignedMultisigTransactionBroadcaster to FullNodeBuilderSidechainRuntimeFeatureExtension.AddFederationGateway().

* Test for LeaderProvidersStream.

* Tests for SignedMultisigTransactionBroadcaster.

* Add documentaton comments.

* Updates to code after latest merge.

Update tests.

Component now uses GetTransactionsByStatusAsync().

* Updates after PR review.

Log the  correct information in the LeaderReceiver class.

Check from txn emptiness in BroadcastTransactionsAsync().

Update tests accordingly.

* Add guard clause to ctors.

* White space clean up.

* Nodesettings changed to include FederatedPegNetwork.

* change the prefixes (#192)

Looks good.

* Fix deposit to store feeding mechanism (#188)

* Add MaturedBlocksProvider

* Add RestMaturedBlockRequester

* Add MaturedConfirmations to BlockTipModel

* Fix incorrect GetNewlyMaturedBlock method

* Make heights in CrossChainTransfer nullable

* Refactor CrossChainStore

* Fix tests not to send blocks to store in random order

* Replace ResyncMaturedBlockDeposits with GetMaturedBlockDeposits

* Add new interfaces to FederationGatewayFeature

* Changed MinCoinMaturity default to 0

* Changes based on feedback

* Changes based on feedback 2

* Changes based on feedback 3

* Changes based on feedback 4

* Changes based on feedback 5

* Optimise when to save store tip

* Add stats

* States re-ordered and test improved

* Remove maxDepositHeight

* Small fix to prev commit

* Don't call Receive if no blocks to avoid looping

* Stratis packages upgrade 1.2.4 to 1.2.5 (#193)

* maybe just to share some tool for now (#194)

* BlockObverver.OnNextCore must not try to extract deposits from the latest block (#196)

* Fix deposit extractor

* Improve documenation

* Add a new method for MaturedBlocksProvider

* Update tests

* Address ChainedHeader.Block being null sometimes (#198)

* Fix deposit extractor

* Improve documenation

* Add a new method for MaturedBlocksProvider

* Update tests

* Fix ReceiveMaturedBlocks

* Move methods and add caching to IMaturedBlocksProvider

* Be more specific about when to request more blocks

* Adapt to moved methods

* Fix expectedCallCount in test

* Merge master

* Reduce nesting

* Make GetChainedHeadersAsync private

* Add POA key file generation to script builder (#197)

* maybe just to share some tool for now

* PoaKeyFiles

* remove my name from here :)

* -testnet fixes + --no-build

* mining tests are working OK

* get premine reward into multisig wallet

* powershell fixes

* change for Ferdeen PR review

* add whitelist and gateway nodes to script

* changes from Jeremy's PR

* Add locks and check that the federated wallet manager dealt with any forks (#202)

* Add locks and check fedwalletmanager during forks

* Reformat and reduce whitespace

* Add missing waits

* Back off if errors when send to counter node

* Optimize performance by batching block data

* Avoid large re-orgs

* Add transaction serialization workaround to Initialize method

* Upgrade packages

* Allow minimum deposit confirmations to be changed from config param (for testing) (#206)

* add stratis-dev feed
and remove powershell-core which has become useless for this project

* 1.2.5-beta to 5547

* upgrade from 1.2.5-beta to 1.2.6-beta

* allow MinimumDepositConfirmations from settings

* Fix deposit extractor (#212)

* remove obsolete method (#215)

* remove obsolete method

* remove OpReturnDataType

* better block definition (#218)

after going back and forth on it, the best is to keep things as they are and change hardcoded values before release :(

* Fix testing issues (#213)

* Fix deposit extractor

* Fix PartialTransacionBehavior looping

* Fix RecordLatestMatureDepositsAsync looping

* Optimise CrossChainTransfer's CombineSignatures

* CrossChainTransferStore fixes and improvements

* Make WithdrawalExtractor's ExtractWithdrawalFromTransaction public

* Check whether peer connected beofre broadcasting

* Indicate when store is suspended

* Clean up console

* Remove verbose logging and redundant code from partial tran behaviour

* Update store tests for non-static ValidateTransaction

* Reduce PartialTransactionBehavior verbosity

* Update/add tests

* Add IsFederationActive, UpdateTransientTransactionDetails, CanPersistMatureDeposits

* Include federation status in console

* Update tests to closer reflect test environment

* Remove MinCoinMaturity. Use MaxReorgLength + 1.

* Keep MinCoinMaturity for testing but default to MaxReorgLen + 1

* add SmartContractPoABlockHeader (#220)

* Setup of  FederatedPegTest (#221)

* Use SmartContractPoAConsensusFactory for genesis block generation

* No genesis reward for sidechains

* Find (real) Genesis Block for FederatedPegTest

* Increase Console input limit

* Use RegTest for the local sidechain network

* Add mining FedPubKeys and additional network fields

* updtae to ports to be like Stratis+1

* Update FederatedPegTest.cs

* premine reward back to 20 000 000

* Update FederatedPegTest.cs

* Added checks to the members' script (#226)

* Remove unused method

* Made FederatedPegTest inherot PoANetwork back

* Switch Mining key and multisig key for J

* Remove --no-build parameter
Change colors to be blue and purple
Remove addnode params

* Added some sanity checks in the script
Emptied the values that need to be added by the user so that they have to do it themselves

* Improve stability and fault tolerance (#225)

* Stability improvements

* Refactor duplicate withdrawal checks

* Only broadcast the first partial transaction

* Update test

* typo

* remove unused param comment

* reward should only go to multisig at premine height (#229)

* Fix daemons (#228)

* Fix some SC dependencies (#231)

* Fix the block definition for SmartContracts (#232)

* Fix block definition build method

* Updated powershell script to work with RegTest

* Fix the Build index (#233)

* remove -nobuild from powershell

* replaced PoAConsensusRulesRegistration by SmartContractPoARuleRegistration

* the chain tip is the block before the block being mined

* Fix as per review

* Int test fed node setup and leader test (#230)

* Setup Fed node builder and node runner for integration tests.

Crate TestBase class to be used by tests.

Start working on the LeaderTest - ST-1_Standard_txn_in_sidechain.

* Missing namespace.

* Updates after merging from upstream.

* Fix SidechainNodeRunner.BuildNode used for integration tests.

Point integration tests to RegTest.

* Work in progress - want to get the TestBase changes in.

* Skip leader test.

Missing stringBuilder.AppendLine(); in PowerShellScriptGeneratorAsTests.

* Update PowerShellScriptGeneratorAsTests.cs

* upgrade fullnode from 1.2.6 to 1.2.7 (#236)

* upgrade to release version of FullNode (#238)

* upgrade to release version of FullNode
1.2.6-beta => 3.0.0.0
4.0.0.70 => 4.0.0.71

* remove stratis-dev nuget source

* just to trigger a rebuild

* Add default collection if federationips param is not set (#240)

* Add default collection if federationips param is not set

* Remove unnecessary null check

* Integration tests that include SC  (#235)

* Setup Fed node builder and node runner for integration tests.

Crate TestBase class to be used by tests.

Start working on the LeaderTest - ST-1_Standard_txn_in_sidechain.

* Missing namespace.

* Updates after merging from upstream.

* Some start

* Test connecting nodes

* 2 Tests

* Make runner identical to FedGateway

* Amend test to check for P2SH instead

* TargetSpacing back to 16

Sorry @codingupastorm we really want those changes, but after talking with @bokobza we think it is better to keep target spacing to 16 although it will definitely slow the tests down. I set it back to 16 and merge your changes, we can discuss it tomorrow, I'm not fussed either way !

* xunit runner

* Run xunit integration tests correctly

* Add federationips to make nodes connect

* TargetSpacing

* Running non-stop (#241)

* Remove IEventPersister unneccessary interface method

* Add IWithdrawal to FindWithdrawalTransaction return value

* Add lockObj to EventPersister

* Refactor PartialTransactionBehavior

* Improve ValidateCrossChainTransfers

* remove async suffix

* Setup main and side chain nodes with config (#243)

* Setup Fed node builder and node runner for integration tests.

Crate TestBase class to be used by tests.

Start working on the LeaderTest - ST-1_Standard_txn_in_sidechain.

* Missing namespace.

* Updates after merging from upstream.

* Undo last commit.

* Missing features in SidechainNodeRunner

Add more arguments when setting up the nodes.

* Write required node argumments to config.

* Created node setup test.

* Take master version as local one had unknown changes.

* Connect more nodes on mainchain & sidechain.

* Configured Fody (#245)

Fix: #242

* Make console message less verbose and more useful/understandable (#252)

* Make console message less verbose and more useful/understandable

* Corresponding updates to tests

* Fixing codestyle issues (#253)

* refactoring

* edits

* var for simple types

* private and readonly

* access modifiers

* access modifier

* fix codestyle violations part 2 (#256)

* package upgrade to 3.0.0.0 to 3.0.0.1 (#257)

* package upgrade to 3.0.0.0 to 3.0.0.1
add --no-build back to the script

* fix FederatedPegBlockDefinition constructor

* fix methods in opreturn reader (#261)

* Comments and minor improvements (#264)

* comments and minor changes

* comment

* rename

* fixed assertion

* Wallet cancellation not to throw (#262)

* No tracing for ConcreteConverter.ReadJson (#267)

* Add remove-transactions endpoint (#271)

* Fix sidechain node in tests, differentiate between different node types, and ensure premine can be received (#274)

* improved the dump of NodeStore information (#275)

* RestClient for FederationGatewayController - code architecture improvements (#277)

Before there was one class and one interface per API method call for the REST client. Some classes that implemented that call also were adding logic on top of the call so it's not bare API wrapper. 

Created API client for FederationGatewayController that just calls API and nothing else. 

Next step would be adding polly to support API fails recovery

* Model deserialization bugfix (#280)

* Trace transfer flow (#278)

* Add some tracing

* Use ConsensusManager.GetBlockData instead of the block repository

* Add tracing

* Serialize POS transaction with time stamp

* Update src/Stratis.FederatedPeg.Features.FederationGateway/TargetChain/CrossChainTransferStore.cs

Co-Authored-By: dangershony <dan.gershony@gmail.com>

* Update .gitignore

Co-Authored-By: dangershony <dan.gershony@gmail.com>

* Update src/Stratis.FederatedPeg.Features.FederationGateway/TargetChain/EventsPersister.cs

Co-Authored-By: dangershony <dan.gershony@gmail.com>

* Update src/Stratis.FederatedPeg.Features.FederationGateway/TargetChain/EventsPersister.cs

Co-Authored-By: dangershony <dan.gershony@gmail.com>

* Update src/Stratis.FederatedPeg.Features.FederationGateway/TargetChain/CrossChainTransferStore.cs

Co-Authored-By: dangershony <dan.gershony@gmail.com>

* Fix build

* Upgrade stratis nuget packages (#292)

* Fix broadcaster to check existence on tid vs depid (#296)

* Add GetInfo API endpoint (#291)

Added a very useful endpoint that helps knowing how the federation is set up.
Useful for the dashboard and the test tool.

* Display recent withdrawal information to console (#294)

* Show recent withdrawal information

* Add mempool indicator

* Changes based on feedback

* Fix store startup to process transaction in sorted order (#295)

* Fix store startup to process transaction in sorted order

* Remove redundant argument

* Remove from private method as well

* Added polly (#301)

* Prevent duplicate block requests (#302)

* Logging and codestyle (#304)

* log stats exception

* removed trace logs since we have fody

* logging and codestyle

* fix the logs and add a test for it (#306)

* Codestyle & removed trace entry exit logs (#307)

* Refactoring (#308)

Unused code, xmldocs, moved interfaces next to the implementation

* NuGet update and Dbreeze serialization fix (#309)

Allows the sidechains repo to serialize everything given the changes to the FN Dbreeze serialization and ultimately allows multiple nodes to run in the one process by removing static dependencies.

I haven't actually connected to the network and completed a transfer yet - if someone could do that it would be ace.

* Fix a few small issues (#312)

Fixes the following:

- Call to `GetMoreBlocksAsync` from `FederationGatewayFeature`. These calls should only happen when the mainchain sends the sidechain a matured block that is ahead of the next expected matured block OR when the sidechain want to expedite matters by immediately requesting more blocks following the processing of a batch of blocks.
- An if statement with commented code that should have been removed completely.
- Removal of wallet transactions associated with suspended transfers.
- Invalid script addresses being displayed in console.

* Make tests currently running against FedPeg network run against Stratis too (#313)

Changes as follows:

- Added a network argument to the test class constructor and added a new test class for Stratis that simply derives from the previous test class. This automatically inherits the test cases.
- Made changes to the tests and supporting methods to support cloning chains. Previously we relied on deterministic chain creation.
- Removed a superfluous test case as we are restoring from the chain in each test case anyway.
- Changed arbitrary number of blocks added after funding to instead use `MinCoinMaturity`.

* big warning on inactive federation wallets (#319)

* Add Signature Counts to Console (#317)

See #316

* enable passphrase when deriving extended key in multisig wallet (#322)

* Refactore how we get matured blocks (#318)

Removed `MaturedBlockReceiver`, `RestMaturedBlockRequester`, `EventsPersister`.
Added `MaturedBlocksSyncManager`.


So before we used to have a mix of PULL and PUSH mechanism. Now there is only PULL mechanism.

The PR is not ready for a merge just yet because I need to add tests but it can already be reviewed. It already works and `CrossChainTransferStore` is advancing nicely. 

It looks like this PR already improves the syncing speed and stability by a lot. 

Please test the PR during the review- run the setup.

* Bug fix for MaturedBlocksProvider (#321)

Shouldn't go in before stratisproject/FederatedSidechains#318 is merged and this PR is updated.

After stratisproject/FederatedSidechains#318 I'll be able to remove `IMaturedBlockDeposits ExtractMaturedBlockDeposits(ChainedHeader chainedHeader);` from block provider. Also will need to update some tests

* Remove unused method from FederationWalletManager (#326)

Removes the unused `MultiSigInput` method.

* SC nuget update (#330)

* Fix for: Polly prevents node syncing when counter chain API isn't available. (#329)

Added cancellation to REST API client. 
Removed blocking call from OnNextCore callback

Fix: #310

* Add caching to MaturedBlocksProvider (#334)

* Add caching to MaturedBlocksProvider

* Add a deadline for good measure

* Make sure that the minimum fee is respected (#332)

* Make sure that the minimum fee is respected

* fixed typo

* Removed unused UpdateWhenChainDownloaded method (#336)

* Update sc nugets (#338)

* Fix signature count (#335)

Fixes the "fix" on PR stratisproject/FederatedSidechains#317. ;)

* NuGet fix (#341)

* Cache results of IsFederationActive (961ms) (#327)

The IsFederationActive call takes 961 ms (almost a full second). 

This PR adds a cache of parameters / result values.

* Removed cache from MaturedBlocksProvider and reduced batch side, added 60s timeout (#340)

* Revert "Add caching to MaturedBlocksProvider (#334)"

This reverts commit 4ffdacb.

* exception logging

* Reduce batch size

* make sure we don't trigger timeout

* improved tests by not asserting logs

* fixes per review

* FedPegMain definition (#343)

* Moved coinbase text out of the CreateGenesis method

* removed some unused variables

* Brought the name and cointicker of the networks inline with the definition of the networks

* Brought some more network data for Main inline

* Upgrade # of coins to 100M

* Create new genesis block for Main

* small fix for 323 (#347)

* Clean up warning and associated code-style (#351)

* Add Api endpoint to show federation history

* Clean up warning and associated code style

* Remove newline

* Remove space

* Use StringBuilder

* Change Xunit Retry reference (#352)

* nuget package only exists for net451

* no need for Test SDK on this exe project

* Remove WithdrawalHistoryProvider (#353)

This removes the WithdrawalHistoryProvider class.

* Revert "Remove WithdrawalHistoryProvider" (#354)

Reverts stratisproject/FederatedSidechains#353

* updated to SBFN 3.0.0.4 beta (#355)

* Mnemonic is optional (#356)

* Cirrus parameters (#359)

* NuGet version updates (#360)

The MainChain_To_SideChain test is being a bit sporadic for me, but it has been passing.

* Add federation IPs as seeds (#364)

* tests for FederationWalletController (#357)

* moved fed controller tests file

* init test

* Moved BuildErrorResponse to base class

* Added 3 tests

* 3 more tests

* Revert "tests for FederationWalletController" (#367)

* Revert "tests for FederationWalletController (#357)"

This reverts commit 18e6bc8.

* reintroduced tests

* Cleanup: unused code & interfaces (#358)

* now it builds (#370)

* Fixed carriage return problems on non-windows machines (#372)

* Create .gitattributes

* Fix CR problem?

* Updates to work in new solution

* bump release to v3.0.1.0 (#3281)

* Create new beta version 3020-beta (#3284)

* Extend cold staking on testnet (#3282)

* Update PosMinting.cs (#3285)

typo

* [FS] Skip tests with flag that can be turned off (#3288)

* [FS] Remove unused code (#3289)

* Merge bug-fixes from release/3.0.1.0 (#3290)

* Extend cold staking on testnet (#3283)

* Corrected logic for PowNoRetargeting/PosNoRetargeting (#3286)

* Corrected logic for PowNoRetargeting/PosNoRetargeting

* Act on the review

* Act on review

* Fix test (#3291)

* Added posNoRetargeting to sidechains networks

* Add versions to "deploymentflags" api (#3294)

* Add versions to "deploymentflags" api

* Changes based on feedback

* [FS] Move transaction building to own file (#3292)

* Move transaction building out to own class.

* Add Guard, only for consistency

* Add to DI.

* [Wallet] Added actual spendable amount to the balance call (#3300)

* Extend cold staking on testnet (#3283)

* Corrected logic for PowNoRetargeting/PosNoRetargeting (#3286)

* Corrected logic for PowNoRetargeting/PosNoRetargeting

* Act on the review

* Act on review

* Removed GetSpendableTransactions() in favor of GetSpendableTransactions(int currentChainHeight, Network network, int confirmations = 0)

* Removed the Network param in GetSpendableTransactions in favor of the CoinbaseMaturity value directly.

* Renamed and inversed IsSpendable() to IsSpent() as it's more logically correct.

* Added SpendableAmount to the balance request

* Unit and integration tests

* Add readydata to more integration tests (#3299)

* Add more readydata

* Update MemoryPoolTests.cs

* Update WalletTests.cs

* Fix Ensure_Peer_CanDiscover_Address_From_ConnectedPeers_And_Connect_ToThem (#3295)

* Fix test

* Update PeerSelector.cs

* Act on review

* [SC] Upgrade to Stratis.SmartContracts 1.2.1 (#3262)

* Update NuGets

* Replace references to Gas

* Fix test

* Fix this

* Fix references

* Update package to v1.2.1

* Remove reference

* Bump version after the sidechain commit (#3304)

* Handle Int64 config keys (#3305)

* Update assumevalid hashes for various networks (#3310)

* Update assumevalid hashes for various networks.

* Fix broken network tests.

* Modified ArchiveFileName so that NLog will archive log files into the Logs folder (#3302)

* Fixed peer that were stuck (#3296)

* moved the peersByPeerId.Add earlier

* added cachedHeaders dump in console
compressed the inbound/outbound peer direction dump in console

* fixed padding

* fix nasty bug that was causing peers to stuck (and potentially stuck the node too)

* fixed inconsistency and peer stucking caused by "insufficientInfo" exception

* added trace and created a common method to get consumed headers count

* Act on review

* Fix archive file null

* [FS] Update FederationGatewayFeature to run in new FN (#3317)

* Update FederationGatewayFeature

* Remove more unused

* Remove dead constructor injections

* Only load wallet if it has not already been loaded

* Update doc

* Remove the beta from the release
codingupastorm added a commit to codingupastorm/StratisBitcoinFullNode that referenced this issue Mar 4, 2020
[Tests] Fix CI issue; Create CA tests common project
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants