Example #1
0
        public CheckCollateralFullValidationRuleTests()
        {
            this.ibdMock = new Mock <IInitialBlockDownloadState>();
            this.collateralCheckerMock      = new Mock <ICollateralChecker>();
            this.slotsManagerMock           = new Mock <ISlotsManager>();
            this.counterChainNetworkWrapper = new CounterChainNetworkWrapper(Networks.Stratis.Mainnet());

            this.ibdMock.Setup(x => x.IsInitialBlockDownload()).Returns(false);
            this.slotsManagerMock
            .Setup(x => x.GetFederationMemberForTimestamp(It.IsAny <uint>(), null))
            .Returns(new CollateralFederationMember(new Key().PubKey, new Money(1), "addr1"));

            this.ruleContext = new RuleContext(new ValidationContext(), DateTimeOffset.Now);
            this.ruleContext.ValidationContext.BlockToValidate = new Block(new BlockHeader()
            {
                Time = 5234
            });

            Block block = this.ruleContext.ValidationContext.BlockToValidate;

            block.AddTransaction(new Transaction());

            CollateralHeightCommitmentEncoder encoder = new CollateralHeightCommitmentEncoder();

            byte[] encodedHeight = encoder.EncodeWithPrefix(1000);

            var votingOutputScript = new Script(OpcodeType.OP_RETURN, Op.GetPushOp(encodedHeight));

            block.Transactions[0].AddOutput(Money.Zero, votingOutputScript);

            this.rule        = new CheckCollateralFullValidationRule(this.ibdMock.Object, this.collateralCheckerMock.Object, this.slotsManagerMock.Object, new Mock <IDateTimeProvider>().Object, new PoANetwork(), this.counterChainNetworkWrapper);
            this.rule.Logger = new ExtendedLoggerFactory().CreateLogger(this.rule.GetType().FullName);
            this.rule.Initialize();
        }
        public InteropPoller(NodeSettings nodeSettings, InteropSettings interopSettings, IAsyncProvider asyncProvider, INodeLifetime nodeLifetime,
                             ChainIndexer chainIndexer, IInitialBlockDownloadState initialBlockDownloadState, IFederationManager federationManager, IFederationHistory federationHistory,
                             IFederatedPegBroadcaster federatedPegBroadcaster, IConversionRequestRepository conversionRequestRepository, IInteropTransactionManager interopTransactionManager,
                             CounterChainNetworkWrapper counterChainNetworkWrapper, IETHCompatibleClientProvider clientProvider)
        {
            this.interopSettings             = interopSettings;
            this.clientProvider              = clientProvider;
            this.network                     = nodeSettings.Network;
            this.asyncProvider               = asyncProvider;
            this.nodeLifetime                = nodeLifetime;
            this.chainIndexer                = chainIndexer;
            this.initialBlockDownloadState   = initialBlockDownloadState;
            this.federationManager           = federationManager;
            this.federationHistory           = federationHistory;
            this.federatedPegBroadcaster     = federatedPegBroadcaster;
            this.conversionRequestRepository = conversionRequestRepository;
            this.interopTransactionManager   = interopTransactionManager;
            this.counterChainNetwork         = counterChainNetworkWrapper.CounterChainNetwork;
            this.logger = nodeSettings.LoggerFactory.CreateLogger(this.GetType().FullName);

            this.eventFilterCreationRequired = new Dictionary <DestinationChain, bool>()
            {
                { DestinationChain.ETH, true }
            };
        }
Example #3
0
        public InteropPoller(NodeSettings nodeSettings,
                             InteropSettings interopSettings,
                             IEthereumClientBase ethereumClientBase,
                             IAsyncProvider asyncProvider,
                             INodeLifetime nodeLifetime,
                             ChainIndexer chainIndexer,
                             IInitialBlockDownloadState initialBlockDownloadState,
                             IFederationManager federationManager,
                             IFederationHistory federationHistory,
                             IFederatedPegBroadcaster federatedPegBroadcaster,
                             IConversionRequestRepository conversionRequestRepository,
                             IInteropTransactionManager interopTransactionManager,
                             CounterChainNetworkWrapper counterChainNetworkWrapper)
        {
            this.interopSettings             = interopSettings;
            this.ethereumClientBase          = ethereumClientBase;
            this.network                     = nodeSettings.Network;
            this.asyncProvider               = asyncProvider;
            this.nodeLifetime                = nodeLifetime;
            this.chainIndexer                = chainIndexer;
            this.initialBlockDownloadState   = initialBlockDownloadState;
            this.federationManager           = federationManager;
            this.federationHistory           = federationHistory;
            this.federatedPegBroadcaster     = federatedPegBroadcaster;
            this.conversionRequestRepository = conversionRequestRepository;
            this.interopTransactionManager   = interopTransactionManager;
            this.counterChainNetwork         = counterChainNetworkWrapper.CounterChainNetwork;
            this.logger = nodeSettings.LoggerFactory.CreateLogger(this.GetType().FullName);

            this.firstPoll = true;
        }
Example #4
0
 /// <summary>
 /// The <see cref="WithdrawalHistoryProvider"/> constructor.
 /// </summary>
 /// <param name="network">Network we are running on.</param>
 /// <param name="federatedPegSettings">Federation settings providing access to number of signatures required.</param>
 /// <param name="mempoolManager">Mempool which provides information about transactions in the mempool.</param>
 /// <param name="counterChainNetworkWrapper">Counter chain network.</param>
 public WithdrawalHistoryProvider(
     Network network,
     IFederatedPegSettings federatedPegSettings,
     MempoolManager mempoolManager,
     CounterChainNetworkWrapper counterChainNetworkWrapper)
 {
     this.network = network;
     this.federatedPegSettings = federatedPegSettings;
     this.withdrawalExtractor  = new WithdrawalExtractor(federatedPegSettings, new OpReturnDataReader(counterChainNetworkWrapper), network);
     this.mempoolManager       = mempoolManager;
 }
Example #5
0
 /// <summary>
 /// The <see cref="WithdrawalHistoryProvider"/> constructor.
 /// </summary>
 /// <param name="network">Network we are running on.</param>
 /// <param name="federatedPegSettings">Federation settings providing access to number of signatures required.</param>
 /// <param name="crossChainTransferStore">Store which provides access to the statuses.</param>
 /// <param name="mempoolManager">Mempool which provides information about transactions in the mempool.</param>
 /// <param name="loggerFactory">Logger factory.</param>
 /// <param name="counterChainNetworkWrapper">Counter chain network.</param>
 public WithdrawalHistoryProvider(
     Network network,
     IFederatedPegSettings federatedPegSettings,
     ICrossChainTransferStore crossChainTransferStore,
     MempoolManager mempoolManager,
     ILoggerFactory loggerFactory,
     CounterChainNetworkWrapper counterChainNetworkWrapper)
 {
     this.network = network;
     this.federatedPegSettings    = federatedPegSettings;
     this.crossChainTransferStore = crossChainTransferStore;
     this.withdrawalExtractor     = new WithdrawalExtractor(federatedPegSettings, new OpReturnDataReader(loggerFactory, counterChainNetworkWrapper), network);
     this.mempoolManager          = mempoolManager;
 }
Example #6
0
        public CheckCollateralFullValidationRule(IInitialBlockDownloadState ibdState, ICollateralChecker collateralChecker,
                                                 ISlotsManager slotsManager, IDateTimeProvider dateTime, Network network, CounterChainNetworkWrapper counterChainNetwork)
        {
            this.counterChainNetwork = counterChainNetwork.CounterChainNetwork;
            this.encoder             = new CollateralHeightCommitmentEncoder();
            this.ibdState            = ibdState;
            this.collateralChecker   = collateralChecker;
            this.slotsManager        = slotsManager;
            this.dateTime            = dateTime;

            this.collateralCheckBanDurationSeconds = (int)(network.Consensus.Options as PoAConsensusOptions).TargetSpacingSeconds / 2;
        }
Example #7
0
        /// <summary>
        /// Initializes the cross-chain transfer tests.
        /// </summary>
        /// <param name="network">The network to run the tests for.</param>
        public CrossChainTestBase(Network network = null, Network counterChainNetwork = null)
        {
            this.network                    = network ?? CirrusNetwork.NetworksSelector.Regtest();
            this.counterChainNetwork        = counterChainNetwork ?? Networks.Stratis.Regtest();
            this.counterChainNetworkWrapper = new CounterChainNetworkWrapper(counterChainNetwork);

            NetworkRegistration.Register(this.network);

            this.loggerFactory = Substitute.For <ILoggerFactory>();
            this.nodeLifetime  = new NodeLifetime();
            this.logger        = Substitute.For <ILogger>();
            this.signals       = Substitute.For <ISignals>();
            this.asyncProvider = new AsyncProvider(this.loggerFactory, this.signals, this.nodeLifetime);
            this.loggerFactory.CreateLogger(null).ReturnsForAnyArgs(this.logger);
            this.dateTimeProvider                   = DateTimeProvider.Default;
            this.opReturnDataReader                 = new OpReturnDataReader(this.loggerFactory, this.counterChainNetworkWrapper);
            this.blockRepository                    = Substitute.For <IBlockRepository>();
            this.fullNode                           = Substitute.For <IFullNode>();
            this.withdrawalTransactionBuilder       = Substitute.For <IWithdrawalTransactionBuilder>();
            this.federationWalletManager            = Substitute.For <IFederationWalletManager>();
            this.federationWalletSyncManager        = Substitute.For <IFederationWalletSyncManager>();
            this.FederationWalletTransactionHandler = Substitute.For <IFederationWalletTransactionHandler>();
            this.walletFeePolicy                    = Substitute.For <IWalletFeePolicy>();
            this.connectionManager                  = Substitute.For <IConnectionManager>();
            this.federatedPegBroadcaster            = Substitute.For <IFederatedPegBroadcaster>();
            this.inputConsolidator                  = Substitute.For <IInputConsolidator>();
            this.dBreezeSerializer                  = new DBreezeSerializer(this.network.Consensus.ConsensusFactory);
            this.ibdState                           = Substitute.For <IInitialBlockDownloadState>();
            this.wallet = null;
            this.federatedPegSettings = Substitute.For <IFederatedPegSettings>();
            this.ChainIndexer         = new ChainIndexer(this.network);
            this.federatedPegSettings.GetWithdrawalTransactionFee(Arg.Any <int>()).ReturnsForAnyArgs((x) =>
            {
                int numInputs = x.ArgAt <int>(0);

                return(FederatedPegSettings.BaseTransactionFee + FederatedPegSettings.InputTransactionFee * numInputs);
            });

            // Generate the keys used by the federation members for our tests.
            this.federationKeys = new[]
            {
                "ensure feel swift crucial bridge charge cloud tell hobby twenty people mandate",
                "quiz sunset vote alley draw turkey hill scrap lumber game differ fiction",
                "exchange rent bronze pole post hurry oppose drama eternal voice client state"
            }.Select(m => HdOperations.GetExtendedKey(m)).ToArray();

            SetExtendedKey(0);

            this.fundingTransactions = new List <Transaction>();

            this.blockDict = new Dictionary <uint256, Block>();
            this.blockDict[this.network.GenesisHash] = this.network.GetGenesis();

            this.blockRepository.GetBlocks(Arg.Any <List <uint256> >()).ReturnsForAnyArgs((x) =>
            {
                List <uint256> hashes = x.ArgAt <List <uint256> >(0);
                var blocks            = new List <Block>();
                for (int i = 0; i < hashes.Count; i++)
                {
                    blocks.Add(this.blockDict.TryGetValue(hashes[i], out Block block) ? block : null);
                }

                return(blocks);
            });

            this.blockRepository.GetBlock(Arg.Any <uint256>()).ReturnsForAnyArgs((x) =>
            {
                uint256 hash = x.ArgAt <uint256>(0);
                this.blockDict.TryGetValue(hash, out Block block);

                return(block);
            });

            this.blockRepository.TipHashAndHeight.Returns((x) => {
                return(new HashHeightPair(this.blockDict.Last().Value.GetHash(), this.blockDict.Count - 1));
            });
        }
 public OpReturnDataReader(ILoggerFactory loggerFactory, CounterChainNetworkWrapper counterChainNetworkWrapper)
 {
     this.logger = loggerFactory.CreateLogger("Impleum.Bitcoin.Fullnode");
     this.counterChainNetwork = counterChainNetworkWrapper.CounterChainNetwork;
 }
 public OpReturnDataReader(ILoggerFactory loggerFactory, CounterChainNetworkWrapper counterChainNetworkWrapper)
 {
     this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
     this.counterChainNetwork = counterChainNetworkWrapper.CounterChainNetwork;
 }
Example #10
0
 public OpReturnDataReader(CounterChainNetworkWrapper counterChainNetworkWrapper)
 {
     this.logger = LogManager.GetCurrentClassLogger();
     this.counterChainNetwork = counterChainNetworkWrapper.CounterChainNetwork;
 }
        public FederatedPegSettings(NodeSettings nodeSettings, CounterChainNetworkWrapper counterChainNetworkWrapper)
        {
            Guard.NotNull(nodeSettings, nameof(nodeSettings));

            TextFileConfiguration configReader = nodeSettings.ConfigReader;

            this.IsMainChain = configReader.GetOrDefault("mainchain", false);
            if (!this.IsMainChain && !configReader.GetOrDefault("sidechain", false))
            {
                throw new ConfigurationException("Either -mainchain or -sidechain must be specified");
            }

            string redeemScriptRaw = configReader.GetOrDefault <string>(RedeemScriptParam, null);

            Console.WriteLine(redeemScriptRaw);

            PayToMultiSigTemplateParameters para = null;

            if (!string.IsNullOrEmpty(redeemScriptRaw))
            {
                var redeemScript = new Script(redeemScriptRaw);
                para = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(redeemScript) ??
                       PayToFederationTemplate.Instance.ExtractScriptPubKeyParameters(redeemScript, nodeSettings.Network);
            }

            if (para == null)
            {
                string pubKeys = configReader.GetOrDefault <string>(FederationKeysParam, null);
                if (string.IsNullOrEmpty(pubKeys))
                {
                    throw new ConfigurationException($"Either -{RedeemScriptParam} or -{FederationKeysParam} must be specified.");
                }

                para.PubKeys        = pubKeys.Split(",").Select(s => new PubKey(s.Trim())).ToArray();
                para.SignatureCount = (pubKeys.Length + 1) / 2;
            }

            para.SignatureCount = configReader.GetOrDefault(FederationQuorumParam, para.SignatureCount);

            IFederation federation;

            federation = new Federation(para.PubKeys, para.SignatureCount);
            nodeSettings.Network.Federations.RegisterFederation(federation);
            counterChainNetworkWrapper.CounterChainNetwork.Federations.RegisterFederation(federation);

            this.MultiSigRedeemScript = federation.MultisigScript;
            this.MultiSigAddress      = this.MultiSigRedeemScript.Hash.GetAddress(nodeSettings.Network);
            this.MultiSigM            = para.SignatureCount;
            this.MultiSigN            = para.PubKeys.Length;
            this.FederationPublicKeys = para.PubKeys;

            this.PublicKey = configReader.GetOrDefault <string>(PublicKeyParam, null);

            if (this.FederationPublicKeys.All(p => p != new PubKey(this.PublicKey)))
            {
                throw new ConfigurationException("Please make sure the public key passed as parameter was used to generate the multisig redeem script.");
            }

            // Federation IPs - These are required to receive and sign withdrawal transactions.
            string federationIpsRaw = configReader.GetOrDefault <string>(FederationIpsParam, null);

            if (federationIpsRaw == null)
            {
                throw new ConfigurationException("Federation IPs must be specified.");
            }

            IEnumerable <IPEndPoint> endPoints = federationIpsRaw.Split(',').Select(a => a.ToIPEndPoint(nodeSettings.Network.DefaultPort));

            this.FederationNodeIpEndPoints = new HashSet <IPEndPoint>(endPoints, new IPEndPointComparer());
            this.FederationNodeIpAddresses = new HashSet <IPAddress>(endPoints.Select(x => x.Address), new IPAddressComparer());

            // These values are only configurable for tests at the moment. Fed members on live networks shouldn't play with them.
            this.CounterChainDepositStartBlock = configReader.GetOrDefault(CounterChainDepositBlock, 1);

            this.SmallDepositThresholdAmount  = Money.Coins(configReader.GetOrDefault(ThresholdAmountSmallDepositParam, 50));
            this.NormalDepositThresholdAmount = Money.Coins(configReader.GetOrDefault(ThresholdAmountNormalDepositParam, 1000));

            this.MinimumConfirmationsSmallDeposits        = configReader.GetOrDefault(MinimumConfirmationsSmallDepositsParam, 25);
            this.MinimumConfirmationsNormalDeposits       = configReader.GetOrDefault(MinimumConfirmationsNormalDepositsParam, 80);
            this.MinimumConfirmationsLargeDeposits        = (int)nodeSettings.Network.Consensus.MaxReorgLength + 1;
            this.MinimumConfirmationsDistributionDeposits = (int)nodeSettings.Network.Consensus.MaxReorgLength + 1;

            this.MaximumPartialTransactionThreshold = configReader.GetOrDefault(MaximumPartialTransactionsParam, CrossChainTransferStore.MaximumPartialTransactions);
            this.WalletSyncFromHeight = configReader.GetOrDefault(WalletSyncFromHeightParam, 0);
        }
 public JoinFederationRequestMonitor(VotingManager votingManager, Network network, CounterChainNetworkWrapper counterChainNetworkWrapper, ISignals signals, ILoggerFactory loggerFactory)
 {
     this.signals             = signals;
     this.loggerFactory       = loggerFactory;
     this.logger              = loggerFactory.CreateLogger(this.GetType().FullName);
     this.votingManager       = votingManager;
     this.network             = network;
     this.counterChainNetwork = counterChainNetworkWrapper.CounterChainNetwork;
 }
Example #13
0
 public JoinFederationRequestMonitor(VotingManager votingManager, Network network, CounterChainNetworkWrapper counterChainNetworkWrapper, IFederationManager federationManager, ISignals signals)
 {
     this.signals             = signals;
     this.logger              = LogManager.GetCurrentClassLogger();
     this.votingManager       = votingManager;
     this.network             = network;
     this.counterChainNetwork = counterChainNetworkWrapper.CounterChainNetwork;
     this.federationManager   = federationManager;
     this.pollsCheckedWithJoinFederationRequestMonitor = new HashSet <uint256>();
 }
 public VotingRequestFullValidationRule(IInitialBlockDownloadState ibdState, Network network, CounterChainNetworkWrapper counterChainNetwork, IFederationManager federationManager, VotingManager votingManager) : base()
 {
     this.ibdState            = ibdState;
     this.network             = network;
     this.counterChainNetwork = counterChainNetwork.CounterChainNetwork;
     this.encoder             = new JoinFederationRequestEncoder();
     this.federationManager   = federationManager;
     this.votingManager       = votingManager;
 }