private JObject GetUnconfirmedBalance(string id, JObject response) { var transactions = MemoryPool.Instance().GetTransactions(); var wallet = WalletStore.Instance().GetAuthenticatedWallet(); if (wallet == null) { return(CreateErrorResponse(id, (int)RpcErrorCodes.RPC_WALLET_NOT_FOUND, "No authenticated wallet")); } long unconfirmedBalance = 0; if (wallet.Addresses != null) { var bcAddrs = wallet.Addresses.Select(addr => BlockChainAddress.Deserialize(addr.Hash)); foreach (var memTx in transactions) { var mBcTx = memTx.Transaction as BcBaseTransaction; if (mBcTx == null) { continue; } var balance = _transactionHelper.CalculateBalance(mBcTx, bcAddrs, _network); unconfirmedBalance += balance; } } response["result"] = unconfirmedBalance; return(response); }
public void CheckClientSignature() { var clientKey = KeyStore.GetClientKey(); var clientWallet = BlockChainAddress.Deserialize("12K5LnVWKCu9QGyB39uGAgVSAfBs33PKS96HSL93"); var scriptBuilder = new ScriptBuilder(); var inputScript = scriptBuilder.New() .AddToStack(clientKey.GetSignature()) .AddToStack(clientKey.GetPublicKey()) .Build(); var outputScript = scriptBuilder.New() .AddOperation(OpCodes.OP_DUP) .AddOperation(OpCodes.OP_HASH160) .AddToStack(clientWallet.PublicKeyHash) .AddOperation(OpCodes.OP_EQUALVERIFY) .AddOperation(OpCodes.OP_CHECKSIG) .Build(); var serializedInputScript = inputScript.Serialize(); var serializedOutputScript = outputScript.Serialize(); var deserializedInputScript = Script.Deserialize(serializedInputScript); var deserializedOutputScript = Script.Deserialize(serializedOutputScript); var interpreter = new ScriptInterpreter(); bool isCorrect = interpreter.Check(deserializedInputScript, deserializedOutputScript); Assert.IsTrue(isCorrect); }
/* * [TestMethod] * public void WhenBuildSmartContractTransaction() * { * var code = @" * using System; * public class SimpleTest * { * private string y {get; set;} * private string z; * public string Test2(string parameter) * { * return parameter; * } * private string Test() * { * return ""1""; * } * }"; * var compiler = new DotnetCompiler(); * var smartContract = compiler.Compile(code); * var ba = BuildBlockChainAddress(); * var builder = new TransactionBuilder(); * var script = Script.CreateP2PKHScript(ba.PublicKeyHash); * var nonce = BitConverter.GetBytes(NonceHelper.GetNonceUInt64()); * var transaction = builder * .NewSmartContractTransaction().CreateSmartContract(smartContract, script, "thabart", "test", 0, nonce) * .Build(); * var serializedTransaction = transaction.Serialize(); * var deserializedTx = BaseTransaction.Deserialize(serializedTransaction, TransactionTypes.SmartContract); * string s = ""; * } */ private static BlockChainAddress BuildBlockChainAddress() { var network = Networks.MainNet; var key = Key.Genererate(); var blockChainAddress = new BlockChainAddress(ScriptTypes.P2PKH, network, key); var hash = blockChainAddress.GetSerializedHash(); var deserializedBA = BlockChainAddress.Deserialize(hash); return(deserializedBA); }
public TransactionOut GetTransactionOut(string encodedBcAddr) { if (string.IsNullOrWhiteSpace(encodedBcAddr)) { throw new ArgumentNullException(nameof(encodedBcAddr)); } var bcAddr = BlockChainAddress.Deserialize(encodedBcAddr); var publicKeyHash = bcAddr.PublicKeyHash; return(GetTransactionOut(publicKeyHash)); }
private static BlockChainAddress BuildBlockChainAddress() { var network = Networks.MainNet; var key = Key.Deserialize(new BigInteger("66661394595692466950200829442443674598224300882267065208709422638481412972116609477112206002430829808784107536250360432119209033266013484787698545014625057"), new BigInteger("43102461949956883352376427470284148089747996528740865531180015053863743793176")); //Key.Genererate(); var k2 = Key.Genererate(); var publicKey = new BigInteger(k2.GetPublicKey().ToArray()); var privateKey = k2.GetPrivateKey(); var keyHash = new BigInteger(k2.GetPublicKeyHashed().ToArray()); var blockChainAddress2 = new BlockChainAddress(ScriptTypes.P2PKH, network, k2); var hh = blockChainAddress2.GetSerializedHash(); var h = new BigInteger(key.GetPublicKeyHashed()); var blockChainAddress = new BlockChainAddress(ScriptTypes.P2PKH, network, key); var s = blockChainAddress.GetJson().ToString(); var hash = blockChainAddress.GetSerializedHash(); var deserializedBA = BlockChainAddress.Deserialize(hash); return(deserializedBA); }
private JObject ListUnspent(IEnumerable <string> parameters, JObject response, string id) { var transactions = MemoryPool.Instance().GetTransactions(); var blockChain = _blockChainStore.GetBlockChain(); var wallet = WalletStore.Instance().GetAuthenticatedWallet(); int confirmationScore = 1; var maxConfirmations = 9999999; IEnumerable <string> addrs = new List <string>(); if (parameters.Any()) { if (int.TryParse(parameters.First().ToString(), out confirmationScore)) { } if (parameters.Count() >= 2 && int.TryParse(parameters.ElementAt(1), out maxConfirmations)) { } if (parameters.Count() >= 3) { var jArr = JArray.Parse(parameters.ElementAt(2)); if (jArr != null) { addrs = jArr.Select(j => j.ToString()); } } } if (wallet == null) { return(CreateErrorResponse(id, (int)RpcErrorCodes.RPC_WALLET_NOT_FOUND, "No authenticated wallet")); } var res = new JArray(); if (addrs == null || !addrs.Any()) { addrs = wallet.Addresses.Select(a => a.Hash); } var walletBlockChainAddrs = addrs.Select(a => new { bca = BlockChainAddress.Deserialize(a), hash = a }); if (maxConfirmations >= 0) // CONFIRMATION 0. { if (transactions != null && transactions.Any()) { foreach (var unconfirmedTransaction in transactions) { if (unconfirmedTransaction.Transaction != null) { var lBcTx = unconfirmedTransaction.Transaction as BcBaseTransaction; if (lBcTx == null) { continue; } foreach (var unconfirmedUTXO in lBcTx.TransactionOut.Where(t => t is TransactionOut).Select(t => t as TransactionOut)) { var bcAdr = walletBlockChainAddrs.FirstOrDefault(wph => unconfirmedUTXO.Script.ContainsPublicKeyHash(wph.bca.PublicKeyHash)); if (bcAdr == null) { continue; } var record = new JObject(); record.Add("txid", unconfirmedTransaction.Transaction.GetTxId().ToHexString()); record.Add("vout", lBcTx.TransactionOut.IndexOf(unconfirmedUTXO)); record.Add("amount", unconfirmedUTXO.Value); record.Add("address", bcAdr.hash); record.Add("scriptPubKey", unconfirmedUTXO.Script.Serialize().ToHexString()); record.Add("confirmations", 0); record.Add("spendable", true); record.Add("solvable", true); res.Add(record); } } } } } if (maxConfirmations >= 1) // CONFIRMATION 1. { var utxos = blockChain.GetUnspentTransactions(); foreach (var utxo in utxos) { var bcAdr = walletBlockChainAddrs.FirstOrDefault(wph => utxo.Script.ContainsPublicKeyHash(wph.bca.PublicKeyHash)); if (bcAdr == null) { continue; } var record = new JObject(); record.Add("txid", utxo.TxId.ToHexString()); record.Add("vout", utxo.Index); record.Add("address", bcAdr.hash); record.Add("scriptPubKey", utxo.Script.Serialize().ToHexString()); record.Add("amount", utxo.Value); record.Add("confirmations", 1); record.Add("spendable", true); record.Add("solvable", true); res.Add(record); } } response["result"] = res; return(response); }
private static void ExecuteConnectedWallet(int number) { if (number < 0 && number > 6) { MenuHelper.DisplayError("Please enter an option between [1-6]"); } switch (number) { case 1: // BROADCAST A UTXO TRANSACTION. Console.WriteLine("Please enter the address"); var receivedHash = Console.ReadLine(); var deserializedAdr = BlockChainAddress.Deserialize(receivedHash); Console.WriteLine("How much do-you want to send ?"); var value = MenuHelper.EnterNumber(); var blockChain = BlockChainStore.Instance().GetBlockChain(); var builder = new TransactionBuilder(); var transaction = builder.NewNoneCoinbaseTransaction() // .Spend(0, ) .AddOutput(value, Script.CreateP2PKHScript(deserializedAdr.PublicKeyHash)) .Build(); var serializedTransaction = transaction.Serialize(); // SEND UTXO. _nodeLauncher.Broadcast(transaction); ExecuteMenu(); return; case 2: // GENERATE A NEW BITCOIN ADDRESS. var key = Key.Genererate(); var h = new BigInteger(key.GetPublicKeyHashed()); var blockChainAddress = new BlockChainAddress(ScriptTypes.P2PKH, _nodeLauncher.GetNetwork(), key); var hash = blockChainAddress.GetSerializedHash(); Console.WriteLine($"Give the bitcoin address to the person {hash}"); Console.WriteLine("Please enter a password to protect your wallet"); var password = Console.ReadLine(); _keyRepository.Load(password); _keyRepository.Keys.Add(key); _keyRepository.Save(password); break; case 3: DisplayWalletInformation(); ExecuteMenu(); return; case 4: _nodeLauncher.RefreshBlockChain(); ExecuteMenu(); break; case 5: _nodeLauncher.RefreshConnectedPeers(); ExecuteMenu(); break; case 6: Console.WriteLine("Bye bye"); Console.ReadLine(); return; } ExecuteMenu(); }
private void SendMoney(object sender, EventArgs e) { var authenticatedWallet = WalletStore.Instance().GetAuthenticatedWallet(); if (authenticatedWallet == null) { MainWindowStore.Instance().DisplayError("You're not authenticated"); return; } var receiverValue = _viewModel.SendValue; var addr = _viewModel.SendAddress; var selectedTransaction = _viewModel.SelectedTransaction; if (selectedTransaction == null) { MainWindowStore.Instance().DisplayError("A transaction must be selected"); return; } if (receiverValue > selectedTransaction.Amount) { return; } var txFee = _transactionHelper.GetMinFee(); var senderValue = selectedTransaction.Amount - receiverValue - txFee; var walletAddr = authenticatedWallet.Addresses.FirstOrDefault(a => a.Hash == selectedTransaction.Hash); if (walletAddr == null) { MainWindowStore.Instance().DisplayError("The selected tranasction is not linked to your wallet"); return; } BlockChainAddress bcAddr = null; try { bcAddr = BlockChainAddress.Deserialize(addr); } catch (Exception) { MainWindowStore.Instance().DisplayError("The address is not correct"); } if (bcAddr == null) { MainWindowStore.Instance().DisplayError("The address is not correct"); return; } var newKey = _walletHelper.CreateNewAddress(); var kh = new BigInteger(newKey.GetPublicKeyHashed()); var script = _scriptBuilder.New() .AddToStack(walletAddr.Key.GetSignature()) .AddToStack(walletAddr.Key.GetPublicKey()) .Build(); var pp = walletAddr.Key.GetPublicKeyHashed(); var senderSript = _scriptBuilder.New() // SEND MONEY TO MY WALLET. .AddOperation(OpCodes.OP_DUP) .AddOperation(OpCodes.OP_HASH160) .AddToStack(newKey.GetPublicKeyHashed()) .AddOperation(OpCodes.OP_EQUALVERIFY) .AddOperation(OpCodes.OP_CHECKSIG) .Build(); var receiverScript = _scriptBuilder.New() // SEND MONEY TO THE SELLER. .AddOperation(OpCodes.OP_DUP) .AddOperation(OpCodes.OP_HASH160) .AddToStack(bcAddr.PublicKeyHash) .AddOperation(OpCodes.OP_EQUALVERIFY) .AddOperation(OpCodes.OP_CHECKSIG) .Build(); var txBuilder = _transactionBuilder.NewNoneCoinbaseTransaction() .Spend(selectedTransaction.TxId.FromHexString(), (uint)selectedTransaction.Vout, script.Serialize()) .AddOutput((long)receiverValue, receiverScript); if (senderValue > 0) { txBuilder.AddOutput((long)senderValue, senderSript); } var tx = txBuilder.Build(); var s = tx.Serialize().Count(); var rpcClient = new RpcClient(authenticatedWallet.Network); rpcClient.SendRawTransaction(tx).ContinueWith((r) => { try { var res = r.Result; } catch (AggregateException ex) { var exx = ex.InnerExceptions; } }); }