Example #1
0
        /// <summary>
        /// Sign a transaction with wallet keys
        /// </summary>
        /// <param name="request">The transaction to be signed</param>
        /// <returns>The signed transaction</returns>
        public async Task <SignRawTransactionResponse> SignRawTransactionWithWalletAsync(SignRawTransactionRequest request)
        {
            Dictionary <string, object> values = new Dictionary <string, object>();

            values.Add("hexstring", request.Transaction.ToHex());

            if (request.PreviousTransactions != null)
            {
                JArray prevs = new JArray();
                foreach (var prev in request.PreviousTransactions)
                {
                    JObject prevObj = new JObject();
                    prevObj.Add(new JProperty("txid", prev.OutPoint.Hash.ToString()));
                    prevObj.Add(new JProperty("vout", prev.OutPoint.N));
                    prevObj.Add(new JProperty("scriptPubKey", prev.ScriptPubKey.ToHex()));
                    if (prev.RedeemScript != null)
                    {
                        prevObj.Add(new JProperty("redeemScript", prev.RedeemScript.ToHex()));
                    }
                    prevObj.Add(new JProperty("amount", prev.Amount.ToDecimal(MoneyUnit.BTC).ToString()));
                    prevs.Add(prevObj);
                }
                values.Add("prevtxs", prevs);

                if (request.SigHash.HasValue)
                {
                    values.Add("sighashtype", SigHashToString(request.SigHash.Value));
                }
            }

            var result = await SendCommandWithNamedArgsAsync("signrawtransactionwithwallet", values).ConfigureAwait(false);

            var response = new SignRawTransactionResponse();

            response.SignedTransaction = ParseTxHex(result.Result["hex"].Value <string>());
            response.Complete          = result.Result["complete"].Value <bool>();
            var errors    = result.Result["errors"] as JArray;
            var errorList = new List <SignRawTransactionResponse.ScriptError>();

            if (errors != null)
            {
                foreach (var error in errors)
                {
                    var scriptError = new SignRawTransactionResponse.ScriptError();
                    scriptError.OutPoint  = OutPoint.Parse($"{error["txid"].Value<string>()}-{(int)error["vout"].Value<long>()}");
                    scriptError.ScriptSig = Script.FromBytesUnsafe(Encoders.Hex.DecodeData(error["scriptSig"].Value <string>()));
                    scriptError.Sequence  = new Sequence((uint)error["sequence"].Value <long>());
                    scriptError.Error     = error["error"].Value <string>();
                    errorList.Add(scriptError);
                }
            }
            response.Errors = errorList.ToArray();
            return(response);
        }