/// <summary> /// Make rpc call /// </summary> private async Task RpcCallCommand <T>(IPEndPoint endPoint, string method, string parameters = null, bool deserializeResult = false) { if (string.IsNullOrEmpty(parameters)) { parameters = "[]"; } using (HttpClient wb = new HttpClient()) { var content = new StringContent ( "{\"jsonrpc\": \"2.0\", \"method\": \"" + method + "\", \"params\": " + parameters + ", \"id\":1}", Encoding.UTF8, "application/json" ); var rest = await wb.PostAsync("http://" + endPoint.Address.ToString() + ":" + endPoint.Port.ToString(), content); if (!rest.IsSuccessStatusCode) { _consoleHandler.WriteLine(rest.StatusCode + " - " + rest.ReasonPhrase, ConsoleOutputStyle.Error); return; } var json = JObject.Parse(await rest.Content.ReadAsStringAsync()); if (deserializeResult) { var obj = BinarySerializer.Default.Deserialize <T>(json["result"].Value <string>().HexToBytes()); if (obj is BlockHeader bh) { _blockSigner.Sign(bh); if (bh is Block bb && bb.Transactions != null) { foreach (var tx in bb.Transactions) { _txSigner.Sign(tx); } } } else { if (obj is Transaction tx) { _txSigner.Sign(tx); } } _consoleHandler.WriteObject(obj, PromptOutputStyle.json); } else { _consoleHandler.WriteObject(json, PromptOutputStyle.json); } } }
/// <summary> /// Creates a new token member. /// </summary> /// <param name="memberId">the member ID</param> /// <param name="operations">the operations to apply</param> /// <param name="metadata">the metadata of the operations</param> /// <param name="signer">the signer used to sign the request</param> /// <returns>the created member</returns> public Task <ProtoMember> CreateMember( string memberId, IList <MemberOperation> operations, IList <MemberOperationMetadata> metadata, ISigner signer) { var update = new MemberUpdate { MemberId = memberId, Operations = { operations } }; var request = new UpdateMemberRequest { Update = update, UpdateSignature = new Signature { MemberId = memberId, KeyId = signer.GetKeyId(), Signature_ = signer.Sign(update) }, Metadata = { metadata } }; return(gateway.UpdateMemberAsync(request) .ToTask(response => response.Member)); }
public override Script GenerateScriptSig(Network network, Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { var multiSigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); var signatures = new TransactionSignature[multiSigParams.PubKeys.Length]; var keys = multiSigParams .PubKeys .Select(p => keyRepo.FindKey(p.ScriptPubKey)) .ToArray(); var sigCount = 0; for (var i = 0; i < keys.Length; i++) { if (sigCount == multiSigParams.SignatureCount) { break; } if (keys[i] != null) { var sig = signer.Sign(keys[i]); signatures[i] = sig; sigCount++; } } IEnumerable <TransactionSignature> sigs = signatures; if (sigCount == multiSigParams.SignatureCount) { sigs = sigs.Where(s => s != TransactionSignature.Empty && s != null); } return(PayToMultiSigTemplate.Instance.GenerateScriptSig(sigs)); }
public Packet Auth(NodeId remoteNodeId, EncryptionHandshake handshake) { handshake.RemoteNodeId = remoteNodeId; handshake.InitiatorNonce = _cryptoRandom.GenerateRandomBytes(32); handshake.EphemeralPrivateKey = new PrivateKey(_cryptoRandom.GenerateRandomBytes(32)); byte[] staticSharedSecret = BouncyCrypto.Agree(_privateKey, remoteNodeId.PublicKey); byte[] forSigning = staticSharedSecret.Xor(handshake.InitiatorNonce); AuthEip8Message authMessage = new AuthEip8Message(); authMessage.Nonce = handshake.InitiatorNonce; authMessage.PublicKey = _privateKey.PublicKey; authMessage.Signature = _signer.Sign(handshake.EphemeralPrivateKey, new Keccak(forSigning)); byte[] authData = _messageSerializationService.Serialize(authMessage); int size = authData.Length + 32 + 16 + 65; // data + MAC + IV + pub byte[] sizeBytes = size.ToBigEndianByteArray().Slice(2, 2); byte[] packetData = _eciesCipher.Encrypt( remoteNodeId.PublicKey, authData, sizeBytes); handshake.AuthPacket = new Packet(Bytes.Concat(sizeBytes, packetData)); return(handshake.AuthPacket); }
public void Sign(BlockHeader blockHeader) { // Check if the BlockHeader is already signed. if (blockHeader.Hash != null && blockHeader.Hash != UInt256.Zero) { return; } if (blockHeader.MerkleRoot == null) { // Compute hash blockHeader.MerkleRoot = MerkleTree.ComputeRoot(blockHeader.TransactionHashes); } var serializedBlockHeader = _binarySerializer.Serialize(blockHeader, new BinarySerializerSettings() { Filter = a => a != nameof(Witness) && a != nameof(Type) && a != nameof(blockHeader.TransactionHashes) }); blockHeader.Hash = new UInt256(_crypto.Hash256(serializedBlockHeader)); _witnessSigner.Sign(blockHeader.Witness); }
public override void Sign(InputSigningContext inputSigningContext, IKeyRepository keyRepository, ISigner signer) { var scriptCode = inputSigningContext.Coin.GetScriptCode(); var multiSigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptCode); TransactionSignature?[] signatures = new TransactionSignature[multiSigParams.PubKeys.Length]; var keys = multiSigParams.PubKeys; int sigcount = 0; for (int i = 0; i < keys.Length && sigcount < multiSigParams.SignatureCount; i++) { var sig = signer.Sign(keys[i]) as TransactionSignature; signatures[i] = sig; if (sig != null) { sigcount++; } } for (int i = 0; i < keys.Length; i++) { var sig = signatures[i]; var key = keys[i]; if (key is PubKey && sig is TransactionSignature s && s != TransactionSignature.Empty) { inputSigningContext.Input.PartialSigs.TryAdd(key, sig); } } }
public void Sign(Block block) { // Compute tx hashes var txSize = block.Transactions?.Length ?? 0; block.TransactionHashes = new UInt256[txSize]; for (var x = 0; x < txSize; x++) { _transactionSigner.Sign(block.Transactions?[x]); block.TransactionHashes[x] = block.Transactions?[x].Hash; } block.MerkleRoot = MerkleTree.ComputeRoot(block.TransactionHashes.ToArray()); // Compute hash var serializedBlock = _binarySerializer.Serialize(block, new BinarySerializerSettings { Filter = a => a != nameof(block.Witness) && a != nameof(block.Transactions) && a != nameof(block.TransactionHashes) && a != nameof(block.Type) }); block.Hash = new UInt256(_crypto.Hash256(serializedBlock)); _witnessOperationsManager.Sign(block.Witness); }
/// <summary> /// Get blocks from stream /// </summary> /// <param name="stream">Stream</param> /// <param name="read_start">Read start index</param> /// <returns>Get block</returns> private IEnumerable <Block> GetBlocks(Stream stream, bool read_start = false) { using (var reader = new BinaryReader(stream)) { var start = read_start ? reader.ReadUInt32() : 0; var count = reader.ReadUInt32(); var end = start + count - 1; if (end <= _blockchainContext.CurrentBlock.Index) { yield break; } using (var progress = _consoleHandler.CreatePercent(count)) { for (var height = start; height <= end; height++) { var array = reader.ReadBytes(reader.ReadInt32()); progress.Value++; if (height > _blockchainContext.CurrentBlock.Index) { var block = BinarySerializer.Default.Deserialize <Block>(array); _blockSigner.Sign(block); yield return(block); } } } } }
public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { var multiSigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); TransactionSignature[] signatures = new TransactionSignature[multiSigParams.PubKeys.Length]; var keys = multiSigParams .PubKeys .Select(p => keyRepo.FindKey(p.ScriptPubKey)) .ToArray(); int sigCount = 0; for(int i = 0 ; i < keys.Length ; i++) { if(sigCount == multiSigParams.SignatureCount) break; if(keys[i] != null) { var sig = signer.Sign(keys[i]); signatures[i] = sig; sigCount++; } } IEnumerable<TransactionSignature> sigs = signatures; if(sigCount == multiSigParams.SignatureCount) { sigs = sigs.Where(s => s != TransactionSignature.Empty && s != null); } return PayToMultiSigTemplate.Instance.GenerateScriptSig(sigs); }
public Transaction BuildTransaction(long gaslimit, byte[] callData, Address sender, BlockHeader parent, IReleaseSpec spec, UInt256 nonce, bool systemTransaction) { Transaction transaction = systemTransaction ? new SystemTransaction() : new Transaction(); UInt256 fee = BaseFeeCalculator.Calculate(parent, spec); transaction.GasPrice = fee; transaction.GasLimit = gaslimit; transaction.To = _entryPointContractAddress; transaction.ChainId = _specProvider.ChainId; transaction.Nonce = nonce; transaction.Value = 0; transaction.Data = callData; transaction.Type = TxType.EIP1559; transaction.DecodedMaxFeePerGas = fee; transaction.SenderAddress = sender; if (!systemTransaction) { _signer.Sign(transaction); } transaction.Hash = transaction.CalculateHash(); return(transaction); }
public async Task <IEnumerable <BlockHeader> > Persist(params BlockHeader[] blockHeaders) { if (blockHeaders == null) { throw new ArgumentNullException(nameof(blockHeaders)); } var blockHeadersToPersist = _blockchainContext.LastBlockHeader == null? blockHeaders .ToList() : // Persisting the Genesis block blockHeaders .Where(bh => bh != null && bh.Index > _blockchainContext.LastBlockHeader.Index) .Distinct(bh => bh.Index) .OrderBy(bh => bh.Index) .ToList(); foreach (var blockHeader in blockHeadersToPersist) { _blockHeaderSigner.Sign(blockHeader); if (!_blockHeaderValidator.IsValid(blockHeader)) { _logger.LogInformation($"Block header with hash {blockHeader.Hash} and index {blockHeader.Index} is invalid and will not be persist."); blockHeadersToPersist.Remove(blockHeader); break; } await _blockRepository.AddBlockHeader(blockHeader); _blockchainContext.LastBlockHeader = blockHeader; } return(blockHeadersToPersist); }
public static UpdateMemberRequest ToUpdateMemberRequest( ProtoMember member, IList <MemberOperation> operations, ISigner signer, IList <MemberOperationMetadata> metadata) { var update = new MemberUpdate { MemberId = member.Id, PrevHash = member.LastHash, Operations = { operations } }; return(new UpdateMemberRequest { Update = update, UpdateSignature = new Signature { MemberId = member.Id, KeyId = signer.GetKeyId(), Signature_ = signer.Sign(update) }, Metadata = { metadata } }); }
/// <inheritdoc /> public override async Task Handle(TransactionMessage message, IPeer sender) { var transaction = message.Payload; if (transaction is MinerTransaction) { return; } if (transaction.Hash == null) { _transactionSigner.Sign(transaction); } if (await _transactionRepository.ContainsTransaction(transaction.Hash)) { _logger.LogInformation($"The transaction \"{transaction.Hash?.ToString(true)}\" exists already on the blockchain."); return; } // Transaction is not added right away but queued to be verified and added. // It is the reason why we do not broadcast immediately. // TODO #374: It is a bit more complicated _transactionPool.Add(transaction); _logger.LogInformation($"Transaction with Hash {transaction.Hash?.ToString(true)} added to the TransactionPool."); }
public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { var key = keyRepo.FindKey(scriptPubKey); if(key == null) return null; var sig = signer.Sign(key); return PayToPubkeyTemplate.Instance.GenerateScriptSig(sig); }
internal void Sign(ISigner signer) { var sb = new StringBuilder(); WriteLicenseProperties(sb); Signature = signer.Sign(sb.ToString()); }
public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { var multiSigParams = EscrowScriptBuilder.ExtractEscrowScriptPubKeyParameters(scriptPubKey); TransactionSignature[] signatures = new TransactionSignature[2]; var keys = multiSigParams .EscrowKeys .Select(p => keyRepo.FindKey(p.ScriptPubKey)) .ToArray(); if (keys.All(k => k == null)) { var redeem = keyRepo.FindKey(multiSigParams.RedeemKey.ScriptPubKey); if (redeem == null) { return(null); } return(new Script(Op.GetPushOp(signer.Sign(redeem).ToBytes()))); } int sigCount = 0; for (int i = 0; i < keys.Length; i++) { if (sigCount == 2) { break; } if (keys[i] != null) { var sig = signer.Sign(keys[i]); signatures[i] = sig; sigCount++; } } IEnumerable <TransactionSignature> sigs = signatures; if (sigCount == 2) { sigs = sigs.Where(s => s != TransactionSignature.Empty && s != null); } return(EscrowScriptBuilder.GenerateScriptSig(sigs.ToArray())); }
private string GetSignature(DateTime utcNow) { GetRequestBuilder builder = new GetRequestBuilder(_builder); builder.AddParam(_tKey, utcNow.ToString("s")); string signature = _signer.Sign(Constants.GET_METHOD, Host, Path, builder.Build()); return(signature); }
public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { var parameters = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); var key = keyRepo.FindKey(parameters.ScriptPubKey); if(key == null) return null; var sig = signer.Sign(key); return PayToPubkeyHashTemplate.Instance.GenerateScriptSig(sig, key.PubKey); }
/// <summary> /// <p><strong>Purpose:</strong></p> <p>This method processes the references and creates the digital signature /// of the contents, and returns the whole XML Node of the signed contents. It produces an XmlNode /// of type signature.</p> /// <p>Note: Current implementation does not create a KeyInfoNode</p> /// </summary> /// <param name="references">references that we will be signing</param> /// <param name="canonicalizer">the specific canonicalizer to use</param> /// <param name="signer">the specific signer to use</param> /// <param name="signID">Signature id</param> /// <returns>Xml Node with digitally signed representation of the data</returns> /// <exception cref="ArgumentNullException">if any element is null</exception> /// <exception cref="SignatureManagerException">any internal exception thrown in this function /// is wrapped up as SignatureManagerException</exception> public XmlNode Sign(IList <IReference> references, InstantiationVO canonicalizer, InstantiationVO signer, string signID) { //Validate not null ExceptionHelper.ValidateNotNull(references, "references"); ExceptionHelper.ValidateNotNull(canonicalizer, "canonicalizer"); ExceptionHelper.ValidateNotNull(signer, "signer"); ExceptionHelper.ValidateNotNull(signID, "signID"); XmlDocument doc = new XmlDocument(); try { //Create Signature node XmlNode signatureNode = doc.CreateNode(XmlNodeType.Element, "Signature", null); //Create SignedInfo Node XmlNode signedInfoNode = CreateSignedInfoNode(doc, canonicalizer, signer, references); //Add an attribute representing default namespace to SignedInfo node //since the two have the exact literal format ((XmlElement)signedInfoNode).SetAttribute("xmlns", DEF_XMLDSIG_NS); //Get Canonicalizer and canonicalize ICanonicalizer canonInst = registry.GetCanonicalizerInstance(canonicalizer.Key, canonicalizer.Params); string canonicalized = canonInst.BringToCanonicalForm(signedInfoNode.OuterXml); //Add SignedInfo node to Signature node signatureNode.InnerXml += canonicalized; //Get Signer Instance, sign, assign to signatureValue node ISigner signerInst = registry.GetSignerInstance(signer.Key, signer.Params); string signed = signerInst.Sign(Encoding.UTF8.GetBytes(canonicalized)); XmlNode signValueNode = CreateSignatureValue(doc, signed); //Append signatureValue to Signature node signatureNode.InnerXml += signValueNode.OuterXml; //Add an attribute representing default namespace to Signature node XmlAttribute defNs = doc.CreateAttribute("xmlns"); defNs.Value = DEF_XMLDSIG_NS; signatureNode.Attributes.Append(defNs); //Add Id attribute to Signature node XmlAttribute idAttr = doc.CreateAttribute("Id"); idAttr.Value = signID; signatureNode.Attributes.Append(idAttr); //Let default namespace takes effect doc.LoadXml(signatureNode.OuterXml); return(doc.DocumentElement); } catch (Exception ex) { throw new SignatureManagerException(SIGN_MAN_EXCP_MSG, ex); } }
protected byte[] Serialize(byte[] type, byte[] data) { byte[] payload = Bytes.Concat(type[0], data); Keccak toSign = Keccak.Compute(payload); Signature signature = _signer.Sign(_privateKey, toSign); byte[] signatureBytes = Bytes.Concat(signature.Bytes, signature.RecoveryId); byte[] mdc = Keccak.Compute(Bytes.Concat(signatureBytes, type, data)).Bytes; return(Bytes.Concat(mdc, signatureBytes, type, data)); }
/// <summary> /// Signs a token payload. /// </summary> /// <param name="payload"></param> /// <param name="keyLevel"></param> /// <returns></returns> public Signature SignTokenPayload(TokenPayload payload, Level keyLevel) { ISigner signer = cryptoEngine.CreateSigner(keyLevel); return(new Signature { KeyId = signer.GetKeyId(), MemberId = MemberId, Signature_ = signer.Sign(Stringify(payload, TokenAction.Endorsed)) }); }
/// <summary> /// Creates new transaction. /// </summary> /// <returns>The transaction.</returns> /// <param name="payload">Payload.</param> public Transaction CreateTransaction(byte[] payload) { var header = new TransactionHeader(); header.FamilyName = settings.FamilyName; header.FamilyVersion = settings.FamilyVersion; header.Inputs.AddRange(settings.Inputs); header.Outputs.AddRange(settings.Outputs); header.Nonce = Guid.NewGuid().ToString(); header.SignerPublicKey = settings.SignerPublickey; header.BatcherPublicKey = settings.BatcherPublicKey; header.PayloadSha512 = payload.ToSha512().ToHexString(); var transaction = new Transaction(); transaction.Payload = ByteString.CopyFrom(payload); transaction.Header = header.ToByteString(); transaction.HeaderSignature = signer.Sign(header.ToByteArray().ToSha256()).ToHexString(); return(transaction); }
public override Script GenerateScriptSig(Network network, Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { Key key = keyRepo.FindKey(scriptPubKey); if (key == null) { return(null); } TransactionSignature sig = signer.Sign(key); return(PayToPubkeyTemplate.Instance.GenerateScriptSig(sig)); }
/* * Подпиывает код */ private string GetSign(string code) { try { return(signer.Sign(code)); } catch (CryptographyException e) { Log.WriteError(e); return(null); } }
private void Sign() { try { Item.Signature = signer.Sign(Item.Content); } catch (CryptographyException ex) { Log.WriteError(ex); Item.SetError(ex.Message, ServiceErrorType.CryptographyError); } }
public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { var key = keyRepo.FindKey(scriptPubKey); if (key == null) { return(null); } var sig = signer.Sign(key); return(PayToPubkeyTemplate.Instance.GenerateScriptSig(sig)); }
public override Script GenerateScriptSig(Network network, Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { KeyId parameters = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); Key key = keyRepo.FindKey(parameters.ScriptPubKey); if (key == null) { return(null); } TransactionSignature sig = signer.Sign(key); return(PayToPubkeyHashTemplate.Instance.GenerateScriptSig(sig, key.PubKey)); }
public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { var offer = SolverScriptBuilder.ExtractOfferScriptParameters(scriptPubKey); var key = keyRepo.FindKey(offer.FulfillKey.ScriptPubKey) ?? keyRepo.FindKey(offer.RedeemKey.ScriptPubKey); if (key == null) { return(null); } var sig = signer.Sign(key); return(new Script(Op.GetPushOp(sig.ToBytes()))); }
public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { var parameters = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); var key = keyRepo.FindKey(parameters.ScriptPubKey); if (key == null) { return(null); } var sig = signer.Sign(key); return(PayToPubkeyHashTemplate.Instance.GenerateScriptSig(sig, key)); }
public string Sign(ISigner signer) { var json = ToJSON(); var data = Utilites.Base64EncodeString(json); var signature = signer.Sign(data); StringBuilder sb = new StringBuilder(); sb.Append(data); sb.Append('.'); sb.Append(System.Convert.ToBase64String(signature)); return(sb.ToString()); }
/// <inheritdoc /> public override Script GenerateScriptSig(Network network, Script scriptPubKey, IKeyRepository keyRepo, ISigner signer) { ColdStakingScriptTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey, out KeyId hotKey, out KeyId coldKey); // The scriptPubKey will be different depending on whether we are spending or cold staking. Key key = keyRepo.FindKey((this.usesColdPubKey ? coldKey : hotKey).ScriptPubKey); if (key == null) { return(null); } TransactionSignature sig = signer.Sign(key); return(ColdStakingScriptTemplate.Instance.GenerateScriptSig(sig, this.usesColdPubKey, key.PubKey)); }
public override void Sign(InputSigningContext inputSigningContext, IKeyRepository keyRepository, ISigner signer) { var scriptCode = inputSigningContext.Coin.GetScriptCode(); var key = keyRepository.FindKey(scriptCode) as PubKey; if (key == null) { return; } var sig = signer.Sign(key) as TransactionSignature; if (sig is null) { return; } inputSigningContext.Input.PartialSigs.TryAdd(key, sig); }
private Block?Seal(Block block) { // Bail out if we're unauthorized to sign a block if (!CanSeal(block.Number, block.ParentHash)) { if (_logger.IsInfo) { _logger.Info($"Not authorized to seal the block {block.ToString(Block.Format.Short)}"); } return(null); } BlockHeader header = block.Header; // Sealing the genesis block is not supported long number = header.Number; if (number == 0) { throw new InvalidOperationException("Can't sign genesis block"); } // For 0-period chains, refuse to seal empty blocks (no reward but would spin sealing) if (_config.BlockPeriod == 0 && block.Transactions.Length == 0) { if (_logger.IsError) { _logger.Error($"Not sealing empty block on 0-period chain {block.Number}"); } throw new InvalidOperationException("An attempt has been made to seal an empty block on a 0-period clique chain"); } // Sign all the things! Keccak headerHash = SnapshotManager.CalculateCliqueHeaderHash(header); Signature signature = _signer.Sign(headerHash); // Copy signature bytes (R and S) var signatureBytes = signature.Bytes; Array.Copy(signatureBytes, 0, header.ExtraData, header.ExtraData.Length - Clique.ExtraSealLength, signatureBytes.Length); // Copy signature's recovery id (V) byte recoveryId = signature.RecoveryId; header.ExtraData[header.ExtraData.Length - 1] = recoveryId; return(block); }