protected override bool CheckScriptSigCore(Script scriptSig, Op[] scriptSigOps, Script scriptPubKey, Op[] scriptPubKeyOps) { if (!scriptSig.IsPushOnly) { return(false); } if (scriptSigOps[0].Code != OpcodeType.OP_0) { return(false); } if (scriptSigOps.Length == 1) { return(false); } if (!scriptSigOps.Skip(1).All(s => TransactionSignature.ValidLength(s.PushData.Length) || s.Code == OpcodeType.OP_0)) { return(false); } if (scriptPubKeyOps != null) { if (!CheckScriptPubKeyCore(scriptPubKey, scriptPubKeyOps)) { return(false); } var sigCountExpected = scriptPubKeyOps[0].GetValue(); return(sigCountExpected == scriptSigOps.Length + 1); } return(true); }
protected override bool CheckScriptSigCore(Network network, Script scriptSig, Op[] scriptSigOps, Script scriptPubKey, Op[] scriptPubKeyOps) { if (!scriptSig.IsPushOnly) { return(false); } if (scriptSigOps[0].Code != OpcodeType.OP_0) { return(false); } if (scriptSigOps.Length == 1) { return(false); } if (!scriptSigOps.Skip(1).All(s => TransactionSignature.ValidLength(s.PushData.Length) || s.Code == OpcodeType.OP_0)) { return(false); } if (scriptPubKeyOps != null) { if (!CheckScriptPubKeyCore(scriptPubKey, scriptPubKeyOps)) { return(false); } (PubKey[] pubKeys, int sigCountExpected) = network.Federations.GetFederation(scriptPubKeyOps[0].PushData).GetFederationDetails(); return(sigCountExpected == scriptSigOps.Length + 1); } return(true); }
bool CheckWitScriptCore(Network network, WitScript witScript) { return(witScript.PushCount == 2 && (witScript[0].Length == 1 && witScript[0][0] == 0 || TransactionSignature.IsValid(network, witScript[0], ScriptVerify.None)) && PubKey.Check(witScript[1], false)); }
protected override bool CheckScriptSigCore(Network network, Script scriptSig, Op[] scriptSigOps, Script scriptPubKey, Op[] scriptPubKeyOps) { Op[] ops = scriptSigOps; if (ops.Length != 1) { return(false); } return(ops[0].PushData != null && TransactionSignature.IsValid(network, ops[0].PushData)); }
public Script GenerateScriptSig(TransactionSignature signature, PubKey publicKey) { if(publicKey == null) throw new ArgumentNullException("publicKey"); return new Script( signature == null ? OpcodeType.OP_0 : Op.GetPushOp(signature.ToBytes()), Op.GetPushOp(publicKey.ToBytes()) ); }
public override bool Equals(object obj) { TransactionSignature item = obj as TransactionSignature; if (item == null) { return(false); } return(Id.Equals(item.Id)); }
public WitScript GenerateWitScript(TransactionSignature signature, PubKey publicKey) { if (publicKey == null) { throw new ArgumentNullException(nameof(publicKey)); } return(new WitScript( signature == null ? OpcodeType.OP_0 : Op.GetPushOp(signature.ToBytes()), Op.GetPushOp(publicKey.ToBytes()) )); }
protected override bool CheckScriptSigCore(Network network, Script scriptSig, Op[] scriptSigOps, Script scriptPubKey, Op[] scriptPubKeyOps) { Op[] ops = scriptSigOps; if (ops.Length != 2) { return(false); } return(ops[0].PushData != null && ((ops[0].Code == OpcodeType.OP_0) || TransactionSignature.IsValid(network, ops[0].PushData, ScriptVerify.None)) && ops[1].PushData != null && PubKey.Check(ops[1].PushData, false)); }
protected override bool CheckScriptSigCore(Script scriptSig, Op[] scriptSigOps, Script?scriptPubKey, Op[]?scriptPubKeyOps) { var ops = scriptSigOps; if (ops.Length != 2) { return(false); } return(ops[0].PushData != null && ((ops[0].Code == OpcodeType.OP_0) || TransactionSignature.IsValid(ops[0].PushData, ScriptVerify.DerSig)) && ops[1].PushData != null && PubKey.SanityCheck(ops[1].PushData)); }
public Script GenerateScriptSig(TransactionSignature signature, PubKey publicKey) { if (signature == null) { throw new ArgumentNullException("signature"); } if (publicKey == null) { throw new ArgumentNullException("publicKey"); } return(new Script( Op.GetPushOp(signature.ToBytes()), Op.GetPushOp(publicKey.ToBytes()) )); }
public TransactionSignature ExtractScriptSigParameters(Script scriptSig) { var ops = scriptSig.ToOps().ToArray(); if(!CheckScriptSigCore(scriptSig, ops, null, null)) return null; var data = ops[0].PushData; if(!TransactionSignature.ValidLength(data.Length)) return null; try { return new TransactionSignature(data); } catch(FormatException) { return null; } }
public TransactionSignature ExtractScriptSigParameters(Network network, Script scriptSig) { Op[] ops = scriptSig.ToOps().ToArray(); if (!CheckScriptSigCore(network, scriptSig, ops, null, null)) { return(null); } byte[] data = ops[0].PushData; if (!TransactionSignature.ValidLength(data.Length)) { return(null); } try { return(new TransactionSignature(data)); } catch (FormatException) { return(null); } }
public static string GetHexSignedTransaction(TransactionToSign txToSign) { var walletPrivateKey = ConfigurationManager.AppSettings[METACO_ENV_WALLET_PRIVATE_KEY_HEX_NAME]; var key = new Key(Encoders.Hex.DecodeData(walletPrivateKey)); var scriptPubKey = PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(key.PubKey); var tx = new Transaction(Encoders.Hex.DecodeData(txToSign.Raw)); foreach(var inputsToSign in txToSign.InputsToSign) { var sigHash = tx.GetSignatureHash(scriptPubKey, inputsToSign.Index); var sig = key.Sign(sigHash); var txSign = new TransactionSignature(sig, SigHash.All); var inputScript = PayToPubkeyHashTemplate.Instance.GenerateScriptSig(txSign, key.PubKey); tx.Inputs[inputsToSign.Index].ScriptSig = inputScript; Assert.True(Script.VerifyScript(scriptPubKey, tx, inputsToSign.Index)); } return tx.ToHex(); }
public Script GenerateScriptSig(TransactionSignature signature, PubKey publicKey) { if(signature == null) throw new ArgumentNullException("signature"); if(publicKey == null) throw new ArgumentNullException("publicKey"); return new Script( Op.GetPushOp(signature.ToBytes()), Op.GetPushOp(publicKey.ToBytes()) ); }
public WitScript GenerateWitScript(TransactionSignature signature, PubKey publicKey) { if(publicKey == null) throw new ArgumentNullException("publicKey"); return new WitScript( signature == null ? OpcodeType.OP_0 : Op.GetPushOp(signature.ToBytes()), Op.GetPushOp(publicKey.ToBytes()) ); }
public Script GenerateScriptSig(TransactionSignature signature) { return new Script( Op.GetPushOp(signature.ToBytes()) ); }
public Script GenerateScriptSig(TransactionSignature[] signatures, Script redeemScript) { List<Op> ops = new List<Op>(); PayToMultiSigTemplate multiSigTemplate = new PayToMultiSigTemplate(); bool multiSig = multiSigTemplate.CheckScriptPubKey(redeemScript); if(multiSig) ops.Add(OpcodeType.OP_0); foreach(var sig in signatures) { ops.Add(sig == null ? OpcodeType.OP_0 : Op.GetPushOp(sig.ToBytes())); } return GenerateScriptSig(ops.ToArray(), redeemScript); }
public Script GenerateScriptSig(TransactionSignature[] signatures) { return GenerateScriptSig((IEnumerable<TransactionSignature>)signatures); }
private static Script CombineMultisig(Script scriptPubKey, TransactionChecker checker, byte[][] sigs1, byte[][] sigs2, HashVersion hashVersion) { // Combine all the signatures we've got: List <TransactionSignature> allsigs = new List <TransactionSignature>(); foreach (var v in sigs1) { if (TransactionSignature.IsValid(v)) { allsigs.Add(new TransactionSignature(v)); } } foreach (var v in sigs2) { if (TransactionSignature.IsValid(v)) { allsigs.Add(new TransactionSignature(v)); } } var multiSigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); if (multiSigParams == null) { throw new InvalidOperationException("The scriptPubKey is not a valid multi sig"); } Dictionary <PubKey, TransactionSignature> sigs = new Dictionary <PubKey, TransactionSignature>(); foreach (var sig in allsigs) { foreach (var pubkey in multiSigParams.PubKeys) { if (sigs.ContainsKey(pubkey)) { continue; // Already got a sig for this pubkey } ScriptEvaluationContext eval = new ScriptEvaluationContext(); if (eval.CheckSig(sig, pubkey, scriptPubKey, checker, hashVersion)) { sigs.AddOrReplace(pubkey, sig); } } } // Now build a merged CScript: int nSigsHave = 0; Script result = new Script(OpcodeType.OP_0); // pop-one-too-many workaround foreach (var pubkey in multiSigParams.PubKeys) { if (sigs.ContainsKey(pubkey)) { result += Op.GetPushOp(sigs[pubkey].ToBytes()); nSigsHave++; } if (nSigsHave >= multiSigParams.SignatureCount) { break; } } // Fill any missing with OP_0: for (int i = nSigsHave; i < multiSigParams.SignatureCount; i++) { result += OpcodeType.OP_0; } return(result); }
private bool CheckSig(byte[] vchSig, byte[] vchPubKey, Script scriptCode, Transaction txTo, int nIn) { //static CSignatureCache signatureCache; if (!PubKey.IsValidSize(vchPubKey.Length)) { return(false); } PubKey pubkey = null; try { pubkey = new PubKey(vchPubKey); } catch (Exception) { return(false); } // Hash type is one byte tacked on to the end of the signature if (vchSig.Length == 0) { return(false); } var scriptSig = new TransactionSignature(vchSig); if (!IsAllowedSignature(scriptSig.SigHash)) { return(false); } uint256 sighash = scriptCode.SignatureHash(txTo, nIn, scriptSig.SigHash); //if (signatureCache.Get(sighash, vchSig, pubkey)) // return true; if (!pubkey.Verify(sighash, scriptSig.Signature)) { if ((ScriptVerify & ScriptVerify.StrictEnc) != 0) { return(false); } //Replicate OpenSSL bug on 23b397edccd3740a74adb603c9756370fafcde9bcc4483eb271ecad09a94dd63 (http://r6.ca/blog/20111119T211504Z.html) var nLenR = vchSig[3]; var nLenS = vchSig[5 + nLenR]; var R = 4; var S = 6 + nLenR; var newS = new Org.BouncyCastle.Math.BigInteger(1, vchSig, S, nLenS); var newR = new Org.BouncyCastle.Math.BigInteger(1, vchSig, R, nLenR); var sig2 = new ECDSASignature(newR, newS); if (sig2.R != scriptSig.Signature.R || sig2.S != scriptSig.Signature.S) { if (!pubkey.Verify(sighash, sig2)) { return(false); } } } //if (!(flags & SCRIPT_VERIFY_NOCACHE)) // signatureCache.Set(sighash, vchSig, pubkey); return(true); }
public async Task <string> WithdrawBtc(string withdrawHash, string recipient, decimal amount) { var coins = new List <UTXO>(); var coinsUsed = new List <UTXO>(); var estimatedFee = await client.GetFeeRateAsync(3); try { await locker.WaitAsync(); while (coinsUsed.Sum(c => c.AsCoin().Amount.ToDecimal(MoneyUnit.BTC)) <= amount) { var txOperations = await client.GetUTXOsAsync(TrackedSource.Create(pubKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main))); foreach (var op in txOperations.Confirmed.UTXOs) { if (!usedInputs.ContainsKey(op.TransactionHash.ToString() + op.Value.Satoshi.ToString())) { coins.Add(op); } } coins.Sort(delegate(UTXO x, UTXO y) { return(-x.AsCoin().Amount.CompareTo(y.AsCoin().Amount)); }); foreach (var item in coins) { if (coinsUsed.Sum(c => c.AsCoin().Amount.ToDecimal(MoneyUnit.BTC)) <= amount) { coinsUsed.Add(item); usedInputs.Add(item.TransactionHash.ToString() + item.Value.Satoshi.ToString(), item); } else { break; } } if (coinsUsed.Sum(c => c.AsCoin().Amount.ToDecimal(MoneyUnit.BTC)) < amount) { await Task.Delay(5000); } } TransactionBuilder builder = null; BitcoinPubKeyAddress destination = null; if (network == NetworkType.Testnet) { builder = Network.TestNet.CreateTransactionBuilder(); destination = new BitcoinPubKeyAddress(recipient, Network.TestNet); } else { builder = Network.Main.CreateTransactionBuilder(); destination = new BitcoinPubKeyAddress(recipient, Network.Main); } NBitcoin.Transaction tx = builder .AddCoins(coinsUsed.Select(c => c.AsCoin() /* .ScriptPubKey.ToBytes()*/)) .Send(destination, Money.Coins(amount)) .Send(TxNullDataTemplate.Instance.GenerateScriptPubKey(Encoding.UTF8.GetBytes(withdrawHash)), Money.Zero) .SetChange(pubKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main)) .SendEstimatedFees((await client.GetFeeRateAsync(3)).FeeRate) .BuildTransaction(sign: false); // Specify the path to unmanaged PKCS#11 library provided by the cryptographic device vendor string pkcs11LibraryPath = @"/opt/cloudhsm/lib/libcloudhsm_pkcs11_standard.so"; // Create factories used by Pkcs11Interop library Net.Pkcs11Interop.HighLevelAPI.Pkcs11InteropFactories factories = new Net.Pkcs11Interop.HighLevelAPI.Pkcs11InteropFactories(); // Load unmanaged PKCS#11 library using (Net.Pkcs11Interop.HighLevelAPI.IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, pkcs11LibraryPath, AppType.MultiThreaded)) { // Show general information about loaded library Net.Pkcs11Interop.HighLevelAPI.ILibraryInfo libraryInfo = pkcs11Library.GetInfo(); Console.WriteLine("Library"); Console.WriteLine(" Manufacturer: " + libraryInfo.ManufacturerId); Console.WriteLine(" Description: " + libraryInfo.LibraryDescription); Console.WriteLine(" Version: " + libraryInfo.LibraryVersion); // Get list of all available slots foreach (Net.Pkcs11Interop.HighLevelAPI.ISlot slot in pkcs11Library.GetSlotList(SlotsType.WithOrWithoutTokenPresent)) { // Show basic information about slot Net.Pkcs11Interop.HighLevelAPI.ISlotInfo slotInfo = slot.GetSlotInfo(); Console.WriteLine(); Console.WriteLine("Slot"); Console.WriteLine(" Manufacturer: " + slotInfo.ManufacturerId); Console.WriteLine(" Description: " + slotInfo.SlotDescription); Console.WriteLine(" Token present: " + slotInfo.SlotFlags.TokenPresent); if (slotInfo.SlotFlags.TokenPresent) { // Show basic information about token present in the slot Net.Pkcs11Interop.HighLevelAPI.ITokenInfo tokenInfo = slot.GetTokenInfo(); Console.WriteLine("Token"); Console.WriteLine(" Manufacturer: " + tokenInfo.ManufacturerId); Console.WriteLine(" Model: " + tokenInfo.Model); Console.WriteLine(" Serial number: " + tokenInfo.SerialNumber); Console.WriteLine(" Label: " + tokenInfo.Label); // Show list of mechanisms (algorithms) supported by the token Console.WriteLine("Supported mechanisms: "); foreach (CKM mechanism in slot.GetMechanismList()) { Console.WriteLine(" " + mechanism); } } using (Net.Pkcs11Interop.HighLevelAPI.ISession session = slot.OpenSession(SessionType.ReadWrite)) { session.Login(CKU.CKU_USER, pkcsUser); // Specify signing mechanism Net.Pkcs11Interop.HighLevelAPI.IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_ECDSA); List <Net.Pkcs11Interop.HighLevelAPI.IObjectAttribute> publicKeyAttributes = new List <Net.Pkcs11Interop.HighLevelAPI.IObjectAttribute>(); publicKeyAttributes.Add(new Net.Pkcs11Interop.HighLevelAPI80.ObjectAttribute(CKA.CKA_LABEL, hsmKey)); publicKeyAttributes.Add(new Net.Pkcs11Interop.HighLevelAPI80.ObjectAttribute(CKA.CKA_SIGN, true)); Net.Pkcs11Interop.HighLevelAPI.IObjectHandle key = session.FindAllObjects(publicKeyAttributes).FirstOrDefault(); uint i = 0; foreach (var c in tx.Inputs.AsIndexedInputs()) { byte[] sourceData = c.GetSignatureHash(coinsUsed.First(cu => cu.Outpoint.Hash == c.PrevOut.Hash).AsCoin()).ToBytes(); Console.WriteLine("sourceData: " + tx.ToHex()); byte[] signature = session.Sign(mechanism, key, sourceData); Console.WriteLine("signature: " + BitConverter.ToString(signature)); var canSig = ECDSASignatureFactory.FromComponents(signature).MakeCanonical(); var sig = new NBitcoin.TransactionSignature(new NBitcoin.Crypto.ECDSASignature(new NBitcoin.BouncyCastle.Math.BigInteger(canSig.R.ToByteArray()), new NBitcoin.BouncyCastle.Math.BigInteger(canSig.S.ToByteArray())), SigHash.Single); builder = builder.AddKnownSignature(pubKey, sig, c.PrevOut); TransactionSignature sig2 = null; if (builder.TrySignInput(tx, i, SigHash.Single, out sig2)) { Console.WriteLine("Input Signed"); Console.WriteLine(BitConverter.ToString(sig2.ToBytes())); } else { Console.WriteLine("Input Not Signed"); } Console.WriteLine("tx: " + tx); i++; tx = builder.SignTransactionInPlace(tx); } Console.WriteLine("tx: " + tx); TransactionPolicyError[] errors = null; if (builder.Verify(tx, out errors)) { var broadcastResult = await client.BroadcastAsync(tx); broadcastResult.ToString(); Console.WriteLine("broadcast: " + tx.GetHash().ToString()); session.Logout(); return(tx.GetHash().ToString()); } else { Console.WriteLine("Verify transaction failed"); } if (errors != null) { foreach (var e in errors) { Console.WriteLine(e.ToString()); } } session.Logout(); } } } return(null); } catch (Exception e) { Log.Error("Failed to send BTC Withdraw" + e.ToString()); throw e; } finally { locker.Release(); } }
private Script CreateScriptSig(TransactionSigningContext ctx, TxIn input, int n, Script scriptPubKey) { var originalScriptSig = input.ScriptSig; input.ScriptSig = scriptPubKey; var pubKeyHashParams = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); if (pubKeyHashParams != null) { var key = FindKey(ctx, pubKeyHashParams); if (key == null) { return(originalScriptSig); } var hash = input.ScriptSig.SignatureHash(ctx.Transaction, n, ctx.SigHash); var sig = key.Sign(hash); return(PayToPubkeyHashTemplate.Instance.GenerateScriptSig(new TransactionSignature(sig, ctx.SigHash), key.PubKey)); } var multiSigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); if (multiSigParams != null) { var alreadySigned = PayToMultiSigTemplate.Instance.ExtractScriptSigParameters(originalScriptSig); if (alreadySigned == null && !Script.IsNullOrEmpty(originalScriptSig)) //Maybe a P2SH { var ops = originalScriptSig.ToOps().ToList(); ops.RemoveAt(ops.Count - 1); alreadySigned = PayToMultiSigTemplate.Instance.ExtractScriptSigParameters(new Script(ops)); } List <TransactionSignature> signatures = new List <TransactionSignature>(); if (alreadySigned != null) { signatures.AddRange(alreadySigned); } var keys = multiSigParams .PubKeys .Select(p => FindKey(ctx, p)) .ToArray(); int sigCount = signatures.Where(s => s != TransactionSignature.Empty && s != null).Count(); for (int i = 0; i < keys.Length; i++) { if (sigCount == multiSigParams.SignatureCount) { break; } if (i >= signatures.Count) { signatures.Add(null); } if (keys[i] != null) { var hash = input.ScriptSig.SignatureHash(ctx.Transaction, n, ctx.SigHash); var sig = keys[i].Sign(hash); signatures[i] = new TransactionSignature(sig, ctx.SigHash); sigCount++; } } IEnumerable <TransactionSignature> sigs = signatures; if (sigCount == multiSigParams.SignatureCount) { sigs = sigs.Where(s => s != TransactionSignature.Empty && s != null); } return(PayToMultiSigTemplate.Instance.GenerateScriptSig(sigs)); } var pubKeyParams = PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); if (pubKeyParams != null) { var key = FindKey(ctx, pubKeyParams); if (key == null) { return(originalScriptSig); } var hash = input.ScriptSig.SignatureHash(ctx.Transaction, n, ctx.SigHash); var sig = key.Sign(hash); return(PayToPubkeyTemplate.Instance.GenerateScriptSig(new TransactionSignature(sig, ctx.SigHash))); } throw new NotSupportedException("Unsupported scriptPubKey"); }
public Script GenerateScriptSig(TransactionSignature signature) { return(new Script( Op.GetPushOp(signature.ToBytes()) )); }
private bool CheckWitScriptCore(WitScript witScript) { return(witScript.PushCount == 2 && ((witScript[0].Length == 1 && witScript[0][0] == 0) || (TransactionSignature.IsValid(witScript[0], ScriptVerify.None))) && PubKey.Check(witScript[1], false)); }
public Script GenerateScriptSig(TransactionSignature[] signatures, Script redeemScript) { List<Op> ops = new List<Op>(); foreach(var sig in signatures) { ops.Add(Op.GetPushOp(sig.ToBytes())); } return GenerateScriptSig(ops.ToArray(), redeemScript); }