public static JoinFederationRequest Deconstruct(Transaction trx, JoinFederationRequestEncoder encoder) { if (trx.Inputs.Count != VotingRequestExpectedInputCount) { return(null); } if (trx.Outputs.Count != VotingRequestExpectedOutputCount) { return(null); } IList <Op> ops = trx.Outputs[1].ScriptPubKey.ToOps(); if (ops[0].Code != OpcodeType.OP_RETURN) { return(null); } if (trx.Outputs[1].Value.ToDecimal(MoneyUnit.BTC) != VotingRequestTransferAmount) { return(null); } return(encoder.Decode(ops[1].PushData)); }
private ChainedHeaderBlock CreateBlockWithVotingRequest(JoinFederationRequest votingRequest, int height) { var encoder = new JoinFederationRequestEncoder(); var votingRequestData = new List <byte>(); votingRequestData.AddRange(encoder.Encode(votingRequest)); var votingRequestOutputScript = new Script(OpcodeType.OP_RETURN, Op.GetPushOp(votingRequestData.ToArray())); Transaction tx = this.network.CreateTransaction(); tx.AddOutput(Money.COIN, votingRequestOutputScript); Block block = new Block(); block.Transactions.Add(tx); block.Header.Time = (uint)(height * (this.network.ConsensusOptions as PoAConsensusOptions).TargetSpacingSeconds); block.UpdateMerkleRoot(); block.GetHash(); return(new ChainedHeaderBlock(block, new ChainedHeader(block.Header, block.GetHash(), height))); }
public async Task CanMineVotingRequestTransactionAsync() { var network = new TestPoACollateralNetwork(true, Guid.NewGuid().ToString()); using (PoANodeBuilder builder = PoANodeBuilder.CreatePoANodeBuilder(this)) { string walletName = "mywallet"; string walletPassword = "******"; string walletAccount = "account 0"; Money transferAmount = Money.Coins(0.01m); Money feeAmount = Money.Coins(0.0001m); var counterchainNetwork = new StraxTest(); CoreNode nodeA = builder.CreatePoANodeWithCounterchain(network, counterchainNetwork, network.FederationKey1).WithWallet(walletPassword, walletName).Start(); CoreNode nodeB = builder.CreatePoANodeWithCounterchain(network, counterchainNetwork, network.FederationKey2).WithWallet(walletPassword, walletName).Start(); TestHelper.Connect(nodeA, nodeB); long toMineCount = network.Consensus.PremineHeight + network.Consensus.CoinbaseMaturity + 1 - nodeA.GetTip().Height; // Get coins on nodeA via the premine. await nodeA.MineBlocksAsync((int)toMineCount).ConfigureAwait(false); CoreNodePoAExtensions.WaitTillSynced(nodeA, nodeB); // Create voting-request transaction. var minerKey = new Key(); var collateralKey = new Key(); var request = new JoinFederationRequest(minerKey.PubKey, new Money(CollateralFederationMember.MinerCollateralAmount, MoneyUnit.BTC), collateralKey.PubKey.Hash); // In practice this signature will come from calling the counter-chain "signmessage" API. request.AddSignature(collateralKey.SignMessage(request.SignatureMessage)); var encoder = new JoinFederationRequestEncoder(nodeA.FullNode.NodeService <Microsoft.Extensions.Logging.ILoggerFactory>()); Transaction trx = JoinFederationRequestBuilder.BuildTransaction(nodeA.FullNode.WalletTransactionHandler(), this.network, request, encoder, walletName, walletAccount, walletPassword); await nodeA.FullNode.NodeController <WalletController>().SendTransaction(new SendTransactionRequest(trx.ToHex())); TestBase.WaitLoop(() => nodeA.CreateRPCClient().GetRawMempool().Length == 1 && nodeB.CreateRPCClient().GetRawMempool().Length == 1); await nodeB.MineBlocksAsync((int)toMineCount).ConfigureAwait(false); TestBase.WaitLoop(() => nodeA.CreateRPCClient().GetRawMempool().Length == 0 && nodeB.CreateRPCClient().GetRawMempool().Length == 0); IWalletManager walletManager = nodeB.FullNode.NodeService <IWalletManager>(); TestBase.WaitLoop(() => { long balance = walletManager.GetBalances(walletName, walletAccount).Sum(x => x.AmountConfirmed); return(balance == feeAmount); }); Assert.Single(nodeA.FullNode.NodeService <VotingManager>().GetPendingPolls()); Assert.Single(nodeB.FullNode.NodeService <VotingManager>().GetPendingPolls()); } }
public async Task <PubKey> JoinFederationAsync(JoinFederationRequestModel request, CancellationToken cancellationToken) { // Get the address pub key hash. var address = BitcoinAddress.Create(request.CollateralAddress, this.counterChainSettings.CounterChainNetwork); KeyId addressKey = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(address.ScriptPubKey); // Get mining key. var keyTool = new KeyTool(this.settings.DataFolder); Key minerKey = keyTool.LoadPrivateKey(); if (minerKey == null) { throw new Exception($"The private key file ({KeyTool.KeyFileDefaultName}) has not been configured."); } var expectedCollateralAmount = CollateralFederationMember.GetCollateralAmountForPubKey(this.network, minerKey.PubKey); Money collateralAmount = new Money(expectedCollateralAmount, MoneyUnit.BTC); var joinRequest = new JoinFederationRequest(minerKey.PubKey, collateralAmount, addressKey); // Populate the RemovalEventId. var collateralFederationMember = new CollateralFederationMember(minerKey.PubKey, false, joinRequest.CollateralAmount, request.CollateralAddress); byte[] federationMemberBytes = (this.network.Consensus.ConsensusFactory as CollateralPoAConsensusFactory).SerializeFederationMember(collateralFederationMember); var votingManager = this.fullNode.NodeService <VotingManager>(); Poll poll = votingManager.GetFinishedPolls().FirstOrDefault(x => x.IsExecuted && x.VotingData.Key == VoteKey.KickFederationMember && x.VotingData.Data.SequenceEqual(federationMemberBytes)); joinRequest.RemovalEventId = (poll == null) ? Guid.Empty : new Guid(poll.PollExecutedBlockData.Hash.ToBytes().TakeLast(16).ToArray()); // Get the signature by calling the counter-chain "signmessage" API. var signMessageRequest = new SignMessageRequest() { Message = joinRequest.SignatureMessage, WalletName = request.CollateralWalletName, Password = request.CollateralWalletPassword, ExternalAddress = request.CollateralAddress }; var walletClient = new WalletClient(this.loggerFactory, this.httpClientFactory, $"http://{this.counterChainSettings.CounterChainApiHost}", this.counterChainSettings.CounterChainApiPort); string signature = await walletClient.SignMessageAsync(signMessageRequest, cancellationToken); if (signature == null) { throw new Exception("Operation was cancelled during call to counter-chain to sign the collateral address."); } joinRequest.AddSignature(signature); var walletTransactionHandler = this.fullNode.NodeService <IWalletTransactionHandler>(); var encoder = new JoinFederationRequestEncoder(this.loggerFactory); Transaction trx = JoinFederationRequestBuilder.BuildTransaction(walletTransactionHandler, this.network, joinRequest, encoder, request.WalletName, request.WalletAccount, request.WalletPassword); var walletService = this.fullNode.NodeService <IWalletService>(); await walletService.SendTransaction(new SendTransactionRequest(trx.ToHex()), cancellationToken); return(minerKey.PubKey); }
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; }
public VotingRequestValidationRule(Network network, ITxMempool mempool, MempoolSettings mempoolSettings, ChainIndexer chainIndexer, ILoggerFactory loggerFactory, VotingManager votingManager, IFederationManager federationManager) : base(network, mempool, mempoolSettings, chainIndexer, loggerFactory) { this.encoder = new JoinFederationRequestEncoder(loggerFactory); this.votingManager = votingManager; this.federationManager = federationManager; }
private ChainedHeaderBlock CreateBlockWithVotingRequest(JoinFederationRequest votingRequest, int height) { var encoder = new JoinFederationRequestEncoder(); var votingRequestData = new List <byte>(); votingRequestData.AddRange(encoder.Encode(votingRequest)); var votingRequestOutputScript = new Script(OpcodeType.OP_RETURN, Op.GetPushOp(votingRequestData.ToArray())); Transaction tx = this.network.CreateTransaction(); tx.AddOutput(Money.COIN, votingRequestOutputScript); Block block = PoaTestHelper.CreateBlock(this.network, tx, height); return(new ChainedHeaderBlock(block, new ChainedHeader(block.Header, block.GetHash(), height))); }
public static bool IsVotingRequestTransaction(Transaction trx, JoinFederationRequestEncoder encoder) { return(Deconstruct(trx, encoder) != null); }
public static Transaction BuildTransaction(IWalletTransactionHandler walletTransactionHandler, Network network, JoinFederationRequest request, JoinFederationRequestEncoder encoder, string walletName, string walletAccount, string walletPassword) { byte[] encodedVotingRequest = encoder.Encode(request); var votingOutputScript = new Script(OpcodeType.OP_RETURN, Op.GetPushOp(encodedVotingRequest)); var context = new TransactionBuildContext(network) { AccountReference = new WalletAccountReference(walletName, walletAccount), MinConfirmations = 0, FeeType = FeeType.High, WalletPassword = walletPassword, Recipients = new[] { new Recipient { Amount = new Money(VotingRequestTransferAmount, MoneyUnit.BTC), ScriptPubKey = votingOutputScript } }.ToList() }; Transaction trx = walletTransactionHandler.BuildTransaction(context); Guard.Assert(IsVotingRequestTransaction(trx, encoder)); Guard.Assert(context.TransactionBuilder.Verify(trx, out _)); return(trx); }
/// <summary>Checks that whomever mined this block is participating in any pending polls to vote-in new federation members.</summary> public override Task RunAsync(RuleContext context) { // Determine the members that this node is currently in favor of adding. List <Poll> pendingPolls = this.ruleEngine.VotingManager.GetPendingPolls(); var encoder = new JoinFederationRequestEncoder(this.loggerFactory); IEnumerable <PubKey> newMembers = pendingPolls .Where(p => p.VotingData.Key == VoteKey.AddFederationMember && (p.PollStartBlockData == null || p.PollStartBlockData.Height <= context.ValidationContext.ChainedHeaderToValidate.Height) && p.PubKeysHexVotedInFavor.Any(pk => pk == this.federationManager.CurrentFederationKey.PubKey.ToHex())) .Select(p => ((CollateralFederationMember)this.consensusFactory.DeserializeFederationMember(p.VotingData.Data)).PubKey); if (!newMembers.Any()) { return(Task.CompletedTask); } // Determine who mined the block. PubKey blockMiner = this.slotsManager.GetFederationMemberForBlock(context.ValidationContext.ChainedHeaderToValidate, this.votingManager).PubKey; // Check that the miner is in favor of adding the same member(s). Dictionary <string, bool> checkList = newMembers.ToDictionary(x => x.ToHex(), x => false); foreach (CollateralFederationMember member in pendingPolls .Where(p => p.VotingData.Key == VoteKey.AddFederationMember && p.PubKeysHexVotedInFavor.Any(pk => pk == blockMiner.ToHex())) .Select(p => (CollateralFederationMember)this.consensusFactory.DeserializeFederationMember(p.VotingData.Data))) { checkList[member.PubKey.ToHex()] = true; } if (!checkList.Any(c => !c.Value)) { return(Task.CompletedTask); } // Otherwise check that the miner is including those votes now. Transaction coinbase = context.ValidationContext.BlockToValidate.Transactions[0]; byte[] votingDataBytes = this.votingDataEncoder.ExtractRawVotingData(coinbase); if (votingDataBytes != null) { List <VotingData> votingDataList = this.votingDataEncoder.Decode(votingDataBytes); foreach (VotingData votingData in votingDataList) { var member = (CollateralFederationMember)this.consensusFactory.DeserializeFederationMember(votingData.Data); var expectedCollateralAmount = CollateralFederationMember.GetCollateralAmountForPubKey((PoANetwork)this.network, member.PubKey); // Check collateral amount. if (member.CollateralAmount.ToDecimal(MoneyUnit.BTC) != expectedCollateralAmount) { this.logger.LogTrace("(-)[INVALID_COLLATERAL_REQUIREMENT]"); PoAConsensusErrors.InvalidCollateralRequirement.Throw(); } // Can't be a multisig member. if (member.IsMultisigMember) { this.logger.LogTrace("(-)[INVALID_MULTISIG_VOTING]"); PoAConsensusErrors.VotingRequestInvalidMultisig.Throw(); } checkList[member.PubKey.ToHex()] = true; } } // If any outstanding votes have not been included throw a consensus error. if (checkList.Any(c => !c.Value)) { PoAConsensusErrors.BlockMissingVotes.Throw(); } return(Task.CompletedTask); }
private void OnBlockConnected(BlockConnected blockConnectedData) { if (!(this.network.Consensus.ConsensusFactory is CollateralPoAConsensusFactory consensusFactory)) { return; } List <Transaction> transactions = blockConnectedData.ConnectedBlock.Block.Transactions; var encoder = new JoinFederationRequestEncoder(this.loggerFactory); for (int i = 0; i < transactions.Count; i++) { Transaction tx = transactions[i]; try { JoinFederationRequest request = JoinFederationRequestBuilder.Deconstruct(tx, encoder); if (request == null) { continue; } // Skip if the member already exists. if (this.votingManager.IsFederationMember(request.PubKey)) { continue; } // Check if the collateral amount is valid. decimal collateralAmount = request.CollateralAmount.ToDecimal(MoneyUnit.BTC); var expectedCollateralAmount = CollateralFederationMember.GetCollateralAmountForPubKey((PoANetwork)this.network, request.PubKey); if (collateralAmount != expectedCollateralAmount) { this.logger.LogDebug("Ignoring voting collateral amount '{0}', when expecting '{1}'.", collateralAmount, expectedCollateralAmount); continue; } // Fill in the request.removalEventId (if any). Script collateralScript = PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(request.CollateralMainchainAddress); var collateralFederationMember = new CollateralFederationMember(request.PubKey, false, request.CollateralAmount, collateralScript.GetDestinationAddress(this.counterChainNetwork).ToString()); byte[] federationMemberBytes = consensusFactory.SerializeFederationMember(collateralFederationMember); // Nothing to do if already voted. if (this.votingManager.AlreadyVotingFor(VoteKey.AddFederationMember, federationMemberBytes)) { this.logger.LogDebug("Skipping because already voted for adding '{0}'.", request.PubKey.ToHex()); continue; } // Populate the RemovalEventId. Poll poll = this.votingManager.GetFinishedPolls().FirstOrDefault(x => x.IsExecuted && x.VotingData.Key == VoteKey.KickFederationMember && x.VotingData.Data.SequenceEqual(federationMemberBytes)); request.RemovalEventId = (poll == null) ? Guid.Empty : new Guid(poll.PollExecutedBlockData.Hash.ToBytes().TakeLast(16).ToArray()); // Check the signature. PubKey key = PubKey.RecoverFromMessage(request.SignatureMessage, request.Signature); if (key.Hash != request.CollateralMainchainAddress) { this.logger.LogDebug("Invalid collateral address validation signature for joining federation via transaction '{0}'", tx.GetHash()); continue; } // Vote to add the member. this.logger.LogDebug("Voting to add federation member '{0}'.", request.PubKey.ToHex()); this.votingManager.ScheduleVote(new VotingData() { Key = VoteKey.AddFederationMember, Data = federationMemberBytes }); } catch (Exception err) { this.logger.LogDebug(err.Message); } } }
public async Task <PubKey> JoinFederationAsync(JoinFederationRequestModel request, CancellationToken cancellationToken) { // Wait until the node is synced before joining. if (this.initialBlockDownloadState.IsInitialBlockDownload()) { throw new Exception($"Please wait until the node is synced with the network before attempting to join the federation."); } // First ensure that this collateral address isnt already present in the federation. if (this.federationManager.GetFederationMembers().IsCollateralAddressRegistered(request.CollateralAddress)) { throw new Exception($"The provided collateral address '{request.CollateralAddress}' is already present in the federation."); } // Get the address pub key hash. BitcoinAddress address = BitcoinAddress.Create(request.CollateralAddress, this.counterChainSettings.CounterChainNetwork); KeyId addressKey = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(address.ScriptPubKey); // Get mining key. var keyTool = new KeyTool(this.nodeSettings.DataFolder); Key minerKey = keyTool.LoadPrivateKey(); if (minerKey == null) { throw new Exception($"The private key file ({KeyTool.KeyFileDefaultName}) has not been configured or is not present."); } var expectedCollateralAmount = CollateralFederationMember.GetCollateralAmountForPubKey(this.network, minerKey.PubKey); var joinRequest = new JoinFederationRequest(minerKey.PubKey, new Money(expectedCollateralAmount, MoneyUnit.BTC), addressKey); // Populate the RemovalEventId. SetLastRemovalEventId(joinRequest, GetFederationMemberBytes(joinRequest, this.network, this.counterChainSettings.CounterChainNetwork), this.votingManager); // Get the signature by calling the counter-chain "signmessage" API. var signMessageRequest = new SignMessageRequest() { Message = joinRequest.SignatureMessage, WalletName = request.CollateralWalletName, Password = request.CollateralWalletPassword, ExternalAddress = request.CollateralAddress }; var walletClient = new WalletClient(this.httpClientFactory, $"http://{this.counterChainSettings.CounterChainApiHost}", this.counterChainSettings.CounterChainApiPort); try { string signature = await walletClient.SignMessageAsync(signMessageRequest, cancellationToken); joinRequest.AddSignature(signature); } catch (Exception err) { throw new Exception($"The call to sign the join federation request failed: '{err.Message}'."); } IWalletTransactionHandler walletTransactionHandler = this.fullNode.NodeService <IWalletTransactionHandler>(); var encoder = new JoinFederationRequestEncoder(); JoinFederationRequestResult result = JoinFederationRequestBuilder.BuildTransaction(walletTransactionHandler, this.network, joinRequest, encoder, request.WalletName, request.WalletAccount, request.WalletPassword); if (result.Transaction == null) { throw new Exception(result.Errors); } IWalletService walletService = this.fullNode.NodeService <IWalletService>(); await walletService.SendTransaction(new SendTransactionRequest(result.Transaction.ToHex()), cancellationToken); return(minerKey.PubKey); }
public void OnBlockConnected(BlockConnected blockConnectedData) { if (!(this.network.Consensus.ConsensusFactory is CollateralPoAConsensusFactory consensusFactory)) { return; } // Only mining federation members vote to include new members. if (this.federationManager.CurrentFederationKey?.PubKey == null) { return; } List <IFederationMember> modifiedFederation = null; List <Transaction> transactions = blockConnectedData.ConnectedBlock.Block.Transactions; var encoder = new JoinFederationRequestEncoder(); for (int i = 0; i < transactions.Count; i++) { Transaction tx = transactions[i]; try { JoinFederationRequest request = JoinFederationRequestBuilder.Deconstruct(tx, encoder); if (request == null) { continue; } // Skip if the member already exists. if (this.votingManager.IsFederationMember(request.PubKey)) { continue; } // Only mining federation members vote to include new members. modifiedFederation ??= this.votingManager.GetModifiedFederation(blockConnectedData.ConnectedBlock.ChainedHeader); if (!modifiedFederation.Any(m => m.PubKey == this.federationManager.CurrentFederationKey.PubKey)) { this.logger.LogDebug($"Ignoring as member '{this.federationManager.CurrentFederationKey.PubKey}' is not part of the federation at block '{blockConnectedData.ConnectedBlock.ChainedHeader}'."); return; } // Check if the collateral amount is valid. decimal collateralAmount = request.CollateralAmount.ToDecimal(MoneyUnit.BTC); var expectedCollateralAmount = CollateralFederationMember.GetCollateralAmountForPubKey((PoANetwork)this.network, request.PubKey); if (collateralAmount != expectedCollateralAmount) { this.logger.LogDebug("Ignoring voting collateral amount '{0}', when expecting '{1}'.", collateralAmount, expectedCollateralAmount); continue; } // Fill in the request.removalEventId (if any). byte[] federationMemberBytes = JoinFederationRequestService.GetFederationMemberBytes(request, this.network, this.counterChainNetwork); // Nothing to do if already voted. if (this.votingManager.AlreadyVotingFor(VoteKey.AddFederationMember, federationMemberBytes)) { this.logger.LogDebug("Skipping because already voted for adding '{0}'.", request.PubKey.ToHex()); continue; } // Populate the RemovalEventId. JoinFederationRequestService.SetLastRemovalEventId(request, federationMemberBytes, this.votingManager); // Check the signature. PubKey key = PubKey.RecoverFromMessage(request.SignatureMessage, request.Signature); if (key.Hash != request.CollateralMainchainAddress) { this.logger.LogDebug("Invalid collateral address validation signature for joining federation via transaction '{0}'", tx.GetHash()); continue; } // Vote to add the member. this.logger.LogDebug("Voting to add federation member '{0}'.", request.PubKey.ToHex()); this.votingManager.ScheduleVote(new VotingData() { Key = VoteKey.AddFederationMember, Data = federationMemberBytes }); } catch (Exception err) { this.logger.LogError(err.Message); } } }