public async Task <IAddressMainInfo> GetMainInfoAsync(string id) { if (BitcoinAddressHelper.IsBitcoinColoredAddress(id, _appSettings.BcnExploler.UsedNetwork())) { var result = new BitcoinColoredAddress(id, _appSettings.BcnExploler.UsedNetwork()); return(new AddressMainInfo { AddressId = id, ColoredAddress = result.ToWif(), UncoloredAddress = result.Address.ToString(), IsColored = true }); } if (BitcoinAddressHelper.IsBitcoinPubKeyAddress(id, _appSettings.BcnExploler.UsedNetwork())) { var result = new BitcoinPubKeyAddress(id, _appSettings.BcnExploler.UsedNetwork()); return(new AddressMainInfo { AddressId = id, ColoredAddress = result.ToColoredAddress().ToWif(), UncoloredAddress = result.ToString(), IsColored = false }); } if (BitcoinAddressHelper.IsBitcoinScriptAddress(id, _appSettings.BcnExploler.UsedNetwork())) { var result = new BitcoinScriptAddress(id, _appSettings.BcnExploler.UsedNetwork()); return(new AddressMainInfo { AddressId = id, ColoredAddress = result.ToColoredAddress().ToWif(), UncoloredAddress = result.ToString(), IsColored = false }); } return(null); }
public void CanGenerateScriptFromAddress() { var address = new BitcoinPubKeyAddress(new KeyId("47376c6f537d62177a2c41c4ca9b45829ab99083"), Network.Main); Assert.Equal("OP_DUP OP_HASH160 47376c6f537d62177a2c41c4ca9b45829ab99083 OP_EQUALVERIFY OP_CHECKSIG", address.ScriptPubKey.ToString()); var scriptAddress = new BitcoinScriptAddress(new ScriptId("8f55563b9a19f321c211e9b9f38cdf686ea07845"), Network.Main); Assert.Equal("OP_HASH160 8f55563b9a19f321c211e9b9f38cdf686ea07845 OP_EQUAL", scriptAddress.ScriptPubKey.ToString()); var pubKey = new PubKey("0359d3092e4a8d5f3b3948235b5dec7395259273ccf3c4e9d5e16695a3fc9588d6"); Assert.Equal("OP_DUP OP_HASH160 4d29186f76581c7375d70499afd1d585149d42cd OP_EQUALVERIFY OP_CHECKSIG", pubKey.Hash.ScriptPubKey.ToString()); Assert.Equal("0359d3092e4a8d5f3b3948235b5dec7395259273ccf3c4e9d5e16695a3fc9588d6 OP_CHECKSIG", pubKey.ScriptPubKey.ToString()); Script script = new Script("0359d3092e4a8d5f3b3948235b5dec7395259273ccf3c4e9d5e16695a3fc9588d6 OP_CHECKSIG"); Assert.Equal("OP_HASH160 a216e3bce8c1b3adf376731b6cd0b6936c4e053f OP_EQUAL", script.PaymentScript.ToString()); }
/// <summary> /// Build a new ready-to-broadcast ledger. /// </summary> /// <param name="operation">Operation code of the ledger</param> /// <param name="toAddress">Receiver's Address (Support string, BitcoinPubKeyAddress, PubKey, Contact)</param> /// <param name="amount">Amount. Nullable if operation is Issue.</param> /// <param name="referenceCode">Additional information attached to ledger</param> /// <returns>Ledger object ready to broadcast.</returns> public Ledger CreateLedger(OperationCode operation, Object toAddress = null, decimal?amount = null, string referenceCode = null) { BitcoinPubKeyAddress toPubAddress = null; if (operation == OperationCode.Issue) { toAddress = contract.OwnerPublicAddress; amount = contract.TotalSupply; } if (toAddress != null) { try { if (toAddress.GetType() == typeof(string)) { toPubAddress = new BitcoinPubKeyAddress(toAddress.ToString(), contractService.MainNetwork); } else if (toAddress.GetType() == typeof(BitcoinPubKeyAddress)) { toPubAddress = toAddress as BitcoinPubKeyAddress; } else if (toAddress.GetType() == typeof(PubKey)) { toPubAddress = (toAddress as PubKey).GetAddress(contractService.MainNetwork); } else if (toAddress.GetType() == typeof(Contact)) { toPubAddress = new BitcoinPubKeyAddress((toAddress as Contact).Address, contractService.MainNetwork); } else { throw new InvalidCastException("Unsupported Type of toAddress"); } } catch (Exception) { throw new InvalidCastException("Unsupported Type of toAddress"); } } byte[] toAddressByte = toPubAddress == null ? null : toPubAddress.ExtractWitnessProgram(); return(CreateLedgerPrivate(operation, toPubAddress, amount, referenceCode)); }
/// <summary> /// Creates a number of addresses in the provided account. /// </summary> /// <param name="account">The account.</param> /// <param name="network">The network.</param> /// <param name="addressesQuantity">The number of addresses to create.</param> /// <param name="isChange">Whether the addresses added are change (internal) addresses or receiving (external) addresses.</param> /// <returns>A list of addresses in Base58.</returns> private List <string> CreateAddressesInAccount(HdAccount account, Network network, int addressesQuantity, bool isChange = false) { List <string> addressesCreated = new List <string>(); var addresses = isChange ? account.InternalAddresses : account.ExternalAddresses; // gets the index of the last address with transactions int firstNewAddressIndex = 0; if (addresses.Any()) { firstNewAddressIndex = addresses.Max(add => add.Index) + 1; } for (int i = firstNewAddressIndex; i < firstNewAddressIndex + addressesQuantity; i++) { // generate new receiving address BitcoinPubKeyAddress address = this.GenerateAddress(account.ExtendedPubKey, i, false, network); // add address details addresses = addresses.Concat(new[] { new HdAddress { Index = i, HdPath = CreateBip44Path(account.GetCoinType(), account.Index, i, isChange), ScriptPubKey = address.ScriptPubKey, Address = address.ToString(), Transactions = new List <TransactionData>() } }); addressesCreated.Add(address.ToString()); } if (isChange) { account.InternalAddresses = addresses; } else { account.ExternalAddresses = addresses; } return(addressesCreated); }
private void Verify_Button_Click(object sender, RoutedEventArgs e) { try { var address = new BitcoinPubKeyAddress(Address.Text, Network.Main); if (address.VerifyMessage(message.Text, signature.Text)) { MessageBox.Show("Signature Verified", "verify Message", MessageBoxButton.OK); } else { MessageBox.Show("Wrong Signature", "verify Message", MessageBoxButton.OK); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Warning", MessageBoxButton.OK); } }
public void Lesson1() { Key key = new Key(); //generates a new private key. PubKey pubKey = key.PubKey; //gets the matching public key. Console.WriteLine("Public Key: {0}", pubKey); KeyId hash = pubKey.Hash; //gets a hash of the public key. Console.WriteLine("Hashed public key: {0}", hash); BitcoinPubKeyAddress address = pubKey.GetAddress(Network.Main); //retrieves the bitcoin address. Console.WriteLine("Address: {0}", address); Script scriptPubKeyFromAddress = address.ScriptPubKey; Console.WriteLine("ScriptPubKey from address: {0}", scriptPubKeyFromAddress); Script scriptPubKeyFromHash = hash.ScriptPubKey; Console.WriteLine("ScriptPubKey from hash: {0}", scriptPubKeyFromHash); }
public IActionResult ValidateAddress([FromQuery] string address) { try { Guard.NotEmpty(address, nameof(address)); var res = new ValidatedAddress { IsValid = false }; // P2WPKH if (BitcoinWitPubKeyAddress.IsValid(address, this.network, out _)) { res.IsValid = true; } // P2WSH else if (BitcoinWitScriptAddress.IsValid(address, this.network, out _)) { res.IsValid = true; } // P2PKH else if (BitcoinPubKeyAddress.IsValid(address, this.network)) { res.IsValid = true; } // P2SH else if (BitcoinScriptAddress.IsValid(address, this.network)) { res.IsValid = true; } return(Json(res)); } catch (Exception e) { this.logger.LogError("Exception occurred: {0}", e.ToString()); return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString())); } }
public void TryGetTargetAddressFromOpReturn_Can_NOT_Read_Transaction_with_two_valid_OpReturns_addresses() { BitcoinPubKeyAddress opReturnAddress1 = this.addressHelper.GetNewTargetChainPubKeyAddress(); byte[] opReturnBytes1 = Encoding.UTF8.GetBytes(opReturnAddress1.ToString()); Transaction transaction = this.transactionBuilder.BuildOpReturnTransaction(this.addressHelper.GetNewSourceChainPubKeyAddress(), opReturnBytes1); BitcoinPubKeyAddress opReturnAddress2 = this.addressHelper.GetNewTargetChainPubKeyAddress(); opReturnAddress1.ToString().Should().NotBe( opReturnAddress2.ToString(), "otherwise the transaction is not ambiguous"); byte[] opReturnBytes2 = Encoding.UTF8.GetBytes(opReturnAddress2.ToString()); transaction.AddOutput(Money.Zero, new Script(OpcodeType.OP_RETURN, Op.GetPushOp(opReturnBytes2))); this.opReturnDataReader.TryGetTargetAddress(transaction, out string addressFromOpReturn); addressFromOpReturn.Should().BeNull(); }
void Start() { Key privateKey = new Key(); // generate a random private key BitcoinSecret mainNetPrivateKey = privateKey.GetBitcoinSecret(Network.Main); // get our private key for the mainnet BitcoinSecret testNetPrivateKey = privateKey.GetBitcoinSecret(Network.TestNet); // get our private key for the testnet UnityEngine.Debug.Log(mainNetPrivateKey); // L5B67zvrndS5c71EjkrTJZ99UaoVbMUAK58GKdQUfYCpAa6jypvn UnityEngine.Debug.Log(testNetPrivateKey); // cVY5auviDh8LmYUW8AfafseD6p6uFoZrP7GjS3rzAerpRKE9Wmuz bool WifIsBitcoinSecret = mainNetPrivateKey == privateKey.GetWif(Network.Main); UnityEngine.Debug.Log(WifIsBitcoinSecret); // True BitcoinSecret bitcoinPrivateKey = privateKey.GetWif(Network.Main); // L5B67zvrndS5c71EjkrTJZ99UaoVbMUAK58GKdQUfYCpAa6jypvn Key samePrivateKey = bitcoinPrivateKey.PrivateKey; PubKey publicKey = privateKey.PubKey; BitcoinPubKeyAddress bitcoinPubicKey = publicKey.GetAddress(Network.Main); // 1PUYsjwfNmX64wS368ZR5FMouTtUmvtmTY //PubKey samePublicKey = bitcoinPubicKey.ItIsNotPossible; }
public void PublicKeyAddressConversion() { foreach (var vector in TestVectorArray.Where(x => x.Type == Base58Type.PUBKEY_ADDRESS)) { var addr = BitcoinAddress.Create(vector.Legacy, Network.Main); Assert.NotNull(addr); var legacyPubKey = new BitcoinPubKeyAddress(vector.Legacy); Assert.Equal(vector.Legacy, legacyPubKey.ToString()); Assert.Equal(Network.Main, legacyPubKey.Network); Assert.Equal(vector.Hash, Encoders.Hex.EncodeData(legacyPubKey.Hash.ToBytes())); var cashAddrPubKey = new BitcoinPubKeyAddress(vector.CashAddr); Assert.Equal(vector.CashAddr, cashAddrPubKey.ToString()); Assert.Equal(Network.Main, cashAddrPubKey.Network); Assert.Equal(vector.Hash, Encoders.Hex.EncodeData(cashAddrPubKey.Hash.ToBytes())); ValidateConversion <BitcoinPubKeyAddress>(vector, addr); } }
public void GenerateWitnessAddressAndVerify() { List <Network> networks = new List <Network>(); networks.Add(new CityMain()); networks.Add(new BitcoinMain()); networks.Add(new StratisMain()); foreach (Network network in networks) { var privateKey = new Key(); BitcoinPubKeyAddress address = privateKey.PubKey.GetAddress(network); var witnessAddress = privateKey.PubKey.WitHash.ToString(); var scriptPubKey = address.ScriptPubKey.ToString(); //Assert.StartsWith("C", address.ToString()); BitcoinSecret secret = privateKey.GetWif(network); var wif = secret.ToWif(); } }
public static Money GetBalance(BitcoinPubKeyAddress address) { QBitNinjaClient client = new QBitNinjaClient(Network.TestNet); var balanceModel = client.GetBalance(address, true).Result; if (balanceModel == null) { return(Money.Zero); } List <BalanceOperation> listBalance = new List <BalanceOperation>(); foreach (var item in balanceModel.Operations) { if (item.Confirmations > 0) { listBalance.Add(item); } } return(new Money((decimal)listBalance.Sum(x => x.Amount.ToDecimal(MoneyUnit.BTC)), MoneyUnit.BTC)); }
public static List <BalanceOperation> GetPending(BitcoinPubKeyAddress address) { QBitNinjaClient client = new QBitNinjaClient(Network.TestNet); var balanceModel = client.GetBalance(address, true).Result; if (balanceModel == null) { return(null); } List <BalanceOperation> listBalance = new List <BalanceOperation>(); foreach (var item in balanceModel.Operations) { if (item.Confirmations == 0) { listBalance.Add(item); } } return(listBalance); }
public void ExtractDepositsFromBlockShouldOnlyGetAmountsGreaterThanWithdrawalFee() { Block block = this.network.Consensus.ConsensusFactory.CreateBlock(); BitcoinPubKeyAddress targetAddress = this.addressHelper.GetNewTargetChainPubKeyAddress(); byte[] opReturnBytes = Encoding.UTF8.GetBytes(targetAddress.ToString()); // Set amount to be less than deposit minimum long depositAmount = FederatedPegSettings.CrossChainTransferMinimum - 1; Transaction depositTransaction = this.transactionBuilder.BuildOpReturnTransaction( this.addressHelper.SourceChainMultisigAddress, opReturnBytes, depositAmount); block.AddTransaction(depositTransaction); this.opReturnDataReader.TryGetTargetAddress(depositTransaction, out string unused1).Returns(callInfo => { callInfo[1] = targetAddress.ToString(); return(true); }); // Set amount to be exactly deposit minimum long secondDepositAmount = FederatedPegSettings.CrossChainTransferMinimum; Transaction secondDepositTransaction = this.transactionBuilder.BuildOpReturnTransaction( this.addressHelper.SourceChainMultisigAddress, opReturnBytes, secondDepositAmount); block.AddTransaction(secondDepositTransaction); this.opReturnDataReader.TryGetTargetAddress(secondDepositTransaction, out string unused2).Returns(callInfo => { callInfo[1] = targetAddress.ToString(); return(true); }); // Set amount to be greater than deposit minimum long thirdDepositAmount = FederatedPegSettings.CrossChainTransferMinimum + 1; Transaction thirdDepositTransaction = this.transactionBuilder.BuildOpReturnTransaction( this.addressHelper.SourceChainMultisigAddress, opReturnBytes, thirdDepositAmount); block.AddTransaction(thirdDepositTransaction); this.opReturnDataReader.TryGetTargetAddress(thirdDepositTransaction, out string unused3).Returns(callInfo => { callInfo[1] = targetAddress.ToString(); return(true); });// Extract deposits int blockHeight = 12345; IReadOnlyList <IDeposit> extractedDeposits = this.depositExtractor.ExtractDepositsFromBlock(block, blockHeight); // Should only be two, with the value just over the withdrawal fee. extractedDeposits.Count.Should().Be(2); foreach (IDeposit extractedDeposit in extractedDeposits) { Assert.True(extractedDeposit.Amount >= FederatedPegSettings.CrossChainTransferMinimum); } }
public ValidatedAddress ValidateAddress(string address) { Guard.NotEmpty(address, nameof(address)); var result = new ValidatedAddress { IsValid = false, Address = address, }; // P2WPKH if (BitcoinWitPubKeyAddress.IsValid(address, this.Network, out Exception _)) { result.IsValid = true; } // P2WSH (unsupported) else if (BitcoinWitScriptAddress.IsValid(address, this.Network, out Exception _)) { result.IsValid = true; } // P2PKH else if (BitcoinPubKeyAddress.IsValid(address, this.Network)) { result.IsValid = true; } // P2SH else if (BitcoinScriptAddress.IsValid(address, this.Network)) { result.IsValid = true; result.IsScript = true; } if (result.IsValid) { var scriptPubKey = BitcoinAddress.Create(address, this.Network).ScriptPubKey; result.ScriptPubKey = scriptPubKey.ToHex(); result.IsWitness = scriptPubKey.IsWitness(this.Network); } return(result); }
static void Test(string[] args) { var bitcoinPrivateKey = new BitcoinSecret("L46GfzE4z24gmX7d3MTWh2dRjTpd6jv4SB3zTB88uvFniMwTbg4B"); var message = "I am ugo the jedi master"; string signature = bitcoinPrivateKey.PrivateKey.SignMessage(message); Console.WriteLine(signature); var address = new BitcoinPubKeyAddress("16LyFzae8r9a1tny8n66gCdrLXUPPcaRm8"); bool isUgoTheJediMaster = address.VerifyMessage(message, signature); Console.WriteLine(isUgoTheJediMaster); //verify nicholas doria is the owner of this address: var nicholasSignature = "H1jiXPzun3rXi0N9v9R5fAWrfEae9WPmlL5DJBj1eTStSvpKdRR8Io6/uT9tGH/3OnzG6ym5yytuWoA9ahkC3dQ="; var nicholasAddress = new BitcoinPubKeyAddress("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB"); var nicholasMessage = "Nicolas Dorier Book Funding Address"; bool isNicholasAddress = nicholasAddress.VerifyMessage(nicholasMessage, nicholasSignature); Console.ReadKey(); }
//秘密鍵・ビットコイン鍵の生成 public static void createKeys() { // 秘密鍵(WIF)の生成 Key key = new Key(); BitcoinSecret secret = key.GetBitcoinSecret(Network.TestNet); Console.WriteLine("Bitcoin Secret(WIF): {0}", secret); // 公開鍵の生成 PubKey pubKey = key.PubKey; Console.WriteLine("Public Key: {0}", pubKey); // ビットコインアドレスの生成 BitcoinPubKeyAddress address = pubKey.GetAddress(Network.TestNet); Console.WriteLine("Address: {0}", address); // Script scriptPubKeyFromAddress = address.ScriptPubKey; // Console.WriteLine("ScriptPubKey from address: {0}", scriptPubKeyFromAddress); }
private static void Main(string[] args) { // Private keys are often represented in Base58Check called a Bitcoin Secret // (also known as Wallet Import Format or simply WIF), like Bitcoin Addresses. var privateKey = new Key(); /* * Note: * it is easy to go from BitcoinSecret to private Key, however * it is impossible to go from a Bitcoin Address to Public Key * because the Bitcoin Address contains a hash of the Public Key, not the Public Key itself. */ // pass in enum value: Main/TestNet, for use on respective networks BitcoinSecret createdWithGetWif = privateKey.GetWif(Network.Main); // method has same body of .GetBitcoinSecret, returns same result BitcoinSecret createdWithGetBitcoinSecret = privateKey.GetBitcoinSecret(Network.Main); var wifIsBitcoinSecret = createdWithGetWif == createdWithGetBitcoinSecret; Console.WriteLine(wifIsBitcoinSecret); // true PubKey publicKey = privateKey.PubKey; BitcoinPubKeyAddress bitcoinPubKey = publicKey.GetAddress(Network.Main); Console.WriteLine(publicKey); Console.WriteLine(bitcoinPubKey); BitcoinEncryptedSecret encryptedBitcoinPrivateKey = createdWithGetWif.Encrypt("ilovecrypto"); Console.WriteLine(encryptedBitcoinPrivateKey); BitcoinSecret secret = encryptedBitcoinPrivateKey.GetSecret("ilovecrypto"); Console.WriteLine(secret); Console.WriteLine(secret == createdWithGetWif); // keep the console open to read Console.ReadLine(); }
public void Send(string toAddress, decimal amount, string message) { var response = GetResponse(); ReceivedCoins = response.ReceivedCoins; var outpointToSpend = GetOutpointToSpend(); CurrentTransaction.Inputs.Add(new TxIn() { PrevOut = outpointToSpend }); var address = new BitcoinPubKeyAddress(toAddress); var transactionAmount = new Money(amount, MoneyUnit.BTC); var minerFee = GetMinerFee(); var txInAmount = (Money)ReceivedCoins[(int)outpointToSpend.N].Amount; Money changeBackAmount = txInAmount - transactionAmount - minerFee; TxOut transactionTxOut = new TxOut() { Value = transactionAmount, ScriptPubKey = address.ScriptPubKey, }; TxOut changeBackTxOut = new TxOut() { Value = changeBackAmount, ScriptPubKey = PrivateKey.ScriptPubKey }; CurrentTransaction.Outputs.Add(transactionTxOut); CurrentTransaction.Outputs.Add(changeBackTxOut); AddMessage(message); Sign(); }
static string[] ReadMsgTxn(string MsgData) { byte[] bts = MsgData.ToLower().HexToByteArray(); string TxnHex = WriteBts(bts, 0, 16).ToHex(); string LinkedTxn = WriteBts(bts, 16, 16).ToHex(); string FromAddress = WriteBts(bts, 32, 20).ToHex(); string Signature = WriteBts(bts, 52, 65).ToHex(); string Message = WriteBts(bts, 117, bts.Length - 117).ToHex(); if (!string.IsNullOrEmpty(LinkedTxn) && LinkedTxn.HexToByteArray().Length != 16) { return(null); } if (TxnHex.HexToByteArray().Length != 16) { return(null); } System.Security.Cryptography.MD5 sha1 = System.Security.Cryptography.MD5.Create(); if (TxnHex != sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(FromAddress + Signature + Message)).ToHex()) { return(null); } Network net = Network.Main; BitcoinPubKeyAddress bitcoinPubKeyAddress = new BitcoinPubKeyAddress(new KeyId(FromAddress.HexToByteArray()), net); Message = System.Text.Encoding.UTF8.GetString(Message.HexToByteArray()); Signature = Convert.ToBase64String(Signature.HexToByteArray()); FromAddress = bitcoinPubKeyAddress.ToString(); if (bitcoinPubKeyAddress.VerifyMessage(Message, Signature) == false) { return(null); } return(new string[] { TxnHex, FromAddress, Signature, Message, LinkedTxn }); }
public Script Lesson1(BitcoinSecret secret = null) { Key key = secret == null ? new Key() : secret.PrivateKey; //generates a new private key. PubKey pubKey = key.PubKey; //gets the matching public key. Console.WriteLine("Public Key: {0}", pubKey); KeyId hash = pubKey.Hash; //gets a hash of the public key. Console.WriteLine("Hashed public key: {0}", hash); secret = secret ?? key.GetBitcoinSecret(network); Console.WriteLine("Bitcoin Secret: {0}", secret); BitcoinPubKeyAddress address = pubKey.GetAddress(network); //retrieves the bitcoin address. Console.WriteLine("Address: {0}", address); Script scriptPubKeyFromAddress = address.ScriptPubKey; Console.WriteLine("ScriptPubKey from address: {0}", scriptPubKeyFromAddress); Script scriptPubKeyFromHash = hash.ScriptPubKey; Console.WriteLine("ScriptPubKey from hash: {0}", scriptPubKeyFromHash); return(scriptPubKeyFromAddress); }
void Sample_02_ScriptPublicKey() { // case 1 KeyId publicKeyHash = new KeyId("14836dbe7f38c5ac3d49e8d790af808a4ee9edcf"); BitcoinAddress bitcoinAddress = publicKeyHash.GetAddress(NBitcoin.Network.TestNet); Debug.Log(bitcoinAddress.ScriptPubKey + " <-------------- Bitcoin Address from public Key Hash"); Script paymentScript = publicKeyHash.ScriptPubKey; BitcoinAddress destination = paymentScript.GetDestinationAddress(NBitcoin.Network.TestNet); Debug.Log(destination.ScriptPubKey + " <-------------- Bitcoin Address from public Key Hash"); // case 2 KeyId sameKeyHash = (KeyId)paymentScript.GetDestination(); BitcoinAddress sameAdress = new BitcoinPubKeyAddress(sameKeyHash, NBitcoin.Network.TestNet); Debug.Log(sameAdress); Debug.Log(publicKeyHash); Debug.Log(sameKeyHash); }
private static void Main(string[] args) { // as the Blockchain is concerned, there is no such thing as a Bitcoin Address. // Internally, the Bitcoin protocol identifies the recipient of Bitcoin by a ScriptPubKey. // e.g., OP_DUP OP_HASH160 14836dbe7f38c5ac3d49e8d790af808a4ee9edcf OP_EQUALVERIFY OP_CHECKSIG // ScriptPubKey explains the conditions that must be met to claim ownership of bitcoin // generate the scriptpubkey from the bitcoin address var publicKeyHash = new KeyId("14836dbe7f38c5ac3d49e8d790af808a4ee9edcf"); var testNetAddress = publicKeyHash.GetAddress(Network.TestNet); var mainNetAddress = publicKeyHash.GetAddress(Network.Main); // scriptpubkeys will contain hash of public key Console.WriteLine(mainNetAddress.ScriptPubKey); Console.WriteLine(testNetAddress.ScriptPubKey); // Bitcoin Addresses are composed of a version byte which identifies the network where to use the address and the hash of a public key. // So we can go backwards and generate a bitcoin address from the ScriptPubKey and the network identifier. var paymentScript = publicKeyHash.ScriptPubKey; var sameMainNetAddress = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine(mainNetAddress == sameMainNetAddress); // also possible to retrieve the hash from the ScriptPubKey and generate a Bitcoin Address from it var samePublicKeyHash = paymentScript.GetDestination() as KeyId; Console.WriteLine(publicKeyHash == samePublicKeyHash); var sameMainNetAddress2 = new BitcoinPubKeyAddress(samePublicKeyHash, Network.Main); Console.WriteLine(mainNetAddress == sameMainNetAddress2); // Note: A ScriptPubKey does not necessarily contain the hashed public key(s) permitted to spend the bitcoin. Console.ReadLine(); }
public void GetBtcBalance( string publicKey, bool isUnspentOnly, out decimal entireBalance, out decimal confirmedBalance) { entireBalance = 0.0M; confirmedBalance = 0.0M; QBitNinjaClient client = new QBitNinjaClient(net); BitcoinPubKeyAddress bitcoinPublicAddress; try { bitcoinPublicAddress = new BitcoinPubKeyAddress(publicKey, net); } catch (Exception) { // For development purposes, we weaken this criteria and don't throw a fatal error on invalid wallet _logger.LogWarning("Unsupported wallet registered as a Bitcoin-type wallet"); entireBalance = confirmedBalance = GetCurrentlyCachedBalance(publicKey).Result; return; } var balance = client.GetBalance(bitcoinPublicAddress, isUnspentOnly).Result; if (balance.Operations.Count > 0) { var unspentCoins = new List <Coin>(); var unspentCoinsConfirmed = new List <Coin>(); foreach (var operation in balance.Operations) { unspentCoins.AddRange(operation.ReceivedCoins.Select(coin => coin as Coin)); if (operation.Confirmations > 0) { unspentCoinsConfirmed.AddRange(operation.ReceivedCoins.Select(coin => coin as Coin)); } } entireBalance = unspentCoins.Sum(x => x.Amount.ToDecimal(MoneyUnit.BTC)); confirmedBalance = unspentCoinsConfirmed.Sum(x => x.Amount.ToDecimal(MoneyUnit.BTC)); } }
public async Task ExtractLargeConversionDeposits_ReturnDeposits_AboveNormalThresholdAsync() { Block block = this.network.Consensus.ConsensusFactory.CreateBlock(); // Create the target address. BitcoinPubKeyAddress targetAddress = this.addressHelper.GetNewTargetChainPubKeyAddress(); byte[] opReturnBytes = Encoding.UTF8.GetBytes(targetAddress.ToString()); // Set amount to be less than deposit minimum CreateDepositTransaction(targetAddress, block, FederatedPegSettings.CrossChainTransferMinimum - 1, opReturnBytes); // Set amount to be less than the small threshold amount. CreateDepositTransaction(targetAddress, block, this.federationSettings.SmallDepositThresholdAmount - 1, opReturnBytes); // Set amount to be exactly the normal threshold amount. CreateDepositTransaction(targetAddress, block, this.federationSettings.NormalDepositThresholdAmount, opReturnBytes); byte[] ethOpReturnBytes = Encoding.UTF8.GetBytes(InterFluxOpReturnEncoder.Encode(DestinationChain.ETH, TargetETHAddress)); // Set amount to be equal to the normal threshold amount. CreateConversionTransaction(block, DepositValidationHelper.ConversionTransactionMinimum - 1, ethOpReturnBytes); // Set amount to be greater than the conversion deposit minimum amount. CreateConversionTransaction(block, DepositValidationHelper.ConversionTransactionMinimum + 1, ethOpReturnBytes); int blockHeight = 12345; IReadOnlyList <IDeposit> extractedDeposits = await this.depositExtractor.ExtractDepositsFromBlock(block, blockHeight, this.retrievalTypeConfirmations); // Should only be 1, with the value just over the withdrawal fee. IEnumerable <IDeposit> applicable = extractedDeposits.Where(d => d.RetrievalType == DepositRetrievalType.ConversionLarge); applicable.Count().Should().Be(1); foreach (IDeposit extractedDeposit in applicable) { Assert.True(extractedDeposit.Amount > DepositValidationHelper.ConversionTransactionMinimum); Assert.Equal(TargetETHAddress, extractedDeposit.TargetAddress); } }
static void Main() { Key privateKey = new Key(); // From the private key, we use a one-way cryptographic function, to generate a public key. PubKey publicKey = privateKey.PubKey; Console.WriteLine(publicKey); // Get your addresses from your public key Console.WriteLine(publicKey.GetAddress(Network.Main)); Console.WriteLine(publicKey.GetAddress(Network.TestNet)); var publicKeyHash = publicKey.Hash; Console.WriteLine(publicKeyHash); var mainNetAddress = publicKeyHash.GetAddress(Network.Main); var testNetAddress = publicKeyHash.GetAddress(Network.TestNet); Console.WriteLine(mainNetAddress); Console.WriteLine(testNetAddress); Console.WriteLine(mainNetAddress.ScriptPubKey); Console.WriteLine(testNetAddress.ScriptPubKey); var paymentScript = publicKeyHash.ScriptPubKey; var sameMainNetAddress = paymentScript.GetDestinationAddress(Network.Main); Console.WriteLine(mainNetAddress == mainNetAddress); var samePublicKeyHash = (KeyId)paymentScript.GetDestination(); Console.WriteLine(publicKeyHash == samePublicKeyHash); var sameMainNetAddress2 = new BitcoinPubKeyAddress(samePublicKeyHash, Network.Main); Console.WriteLine(mainNetAddress == sameMainNetAddress2); }
public static void Execute() { var bitcoinSecret = new BitcoinSecret("cUyeaNoyfYQYC43sxozcyUvwhP6AHQK9ajBqtV23MbdEDxTuxgkT"); string message = "I am Craig Wright"; string signature = bitcoinSecret.PrivateKey.SignMessage(message); Console.WriteLine(signature); // IN5v9+3HGW1q71OqQ1boSZTm0/DCiMpI8E4JB1nD67TCbIVMRk/e3KrTT9GvOuu3NGN0w8R2lWOV2cxnBp+Of8c= // first ever bitcoin address, associated with the // genesis block: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa and verify 'Craig Wright' claim message = "I am Craig Wright"; signature = "IN5v9+3HGW1q71OqQ1boSZTm0/DCiMpI8E4JB1nD67TCbIVMRk/e3KrTT9GvOuu3NGN0w8R2lWOV2cxnBp+Of8c="; var address = new BitcoinPubKeyAddress("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"); bool isCraigWrightSatoshi = address.VerifyMessage(message, signature); Console.WriteLine("Is Craig Wright Satoshi? " + isCraigWrightSatoshi); /* * prove you are the owner of an address without moving coins * Address:1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB * Message:Nicolas Dorier Book Funding Address * Signature:H1jiXPzun3rXi0N9v9R5fAWrfEae9WPmlL5DJBj1eTStSvpKdRR8Io6/uT9tGH/3OnzG6ym5yytuWoA9ahkC3dQ= */ var address2 = "1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB"; var message2 = "Nicolas Dorier Book Funding Address"; var signature2 = "H1jiXPzun3rXi0N9v9R5fAWrfEae9WPmlL5DJBj1eTStSvpKdRR8Io6/uT9tGH/3OnzG6ym5yytuWoA9ahkC3dQ="; //Verify that Nicolas sensei is not lying! var bcAddress = new BitcoinPubKeyAddress(address2); bool isNicolasDorier = bcAddress.VerifyMessage(message2, signature2); Console.WriteLine("Is isNicolasDorier Signature? " + isNicolasDorier); Console.ReadLine(); }
public MaturedBlocksProviderTests() { this.loggerFactory = Substitute.For <ILoggerFactory>(); this.logger = Substitute.For <ILogger>(); this.loggerFactory.CreateLogger(null).ReturnsForAnyArgs(this.logger); this.consensusManager = Substitute.For <IConsensusManager>(); this.network = new CirrusRegTest(); this.mainChainNetwork = new StraxRegTest(); this.opReturnDataReader = Substitute.For <IOpReturnDataReader>(); this.opReturnDataReader.TryGetTargetAddress(null, out string address).Returns(callInfo => { callInfo[1] = null; return(false); }); this.transactionBuilder = new TestTransactionBuilder(); this.addressHelper = new MultisigAddressHelper(this.network, this.mainChainNetwork); this.targetAddress = this.addressHelper.GetNewTargetChainPubKeyAddress(); this.opReturnBytes = Encoding.UTF8.GetBytes(InterFluxOpReturnEncoder.Encode((int)DestinationChain.STRAX, this.targetAddress.ToString())); this.federatedPegSettings = Substitute.For <IFederatedPegSettings>(); this.federatedPegSettings.MultiSigRedeemScript.Returns(this.addressHelper.PayToMultiSig); this.federatedPegSettings.MinimumConfirmationsSmallDeposits.Returns(5); this.federatedPegSettings.MinimumConfirmationsNormalDeposits.Returns(10); this.federatedPegSettings.MinimumConfirmationsLargeDeposits.Returns(20); this.federatedPegSettings.SmallDepositThresholdAmount.Returns(Money.Coins(10)); this.federatedPegSettings.NormalDepositThresholdAmount.Returns(Money.Coins(100)); this.consensusManager.GetBlocksAfterBlock(Arg.Any <ChainedHeader>(), MaturedBlocksProvider.MaturedBlocksBatchSize, Arg.Any <CancellationTokenSource>()).Returns(delegate(CallInfo info) { var chainedHeader = (ChainedHeader)info[0]; if (chainedHeader == null) { return(this.blocks.Where(x => x.ChainedHeader.Height <= this.consensusManager.Tip.Height).ToArray()); } return(this.blocks.SkipWhile(x => x.ChainedHeader.Height <= chainedHeader.Height).Where(x => x.ChainedHeader.Height <= this.consensusManager.Tip.Height).ToArray()); }); }
public void TryGetTargetAddressFromOpReturn_Can_Read_Transaction_with_many_OpReturns_but_only_a_valid_address_one() { BitcoinPubKeyAddress opReturnValidAddress = this.addressHelper.GetNewTargetChainPubKeyAddress(); byte[] opReturnValidAddressBytes = Encoding.UTF8.GetBytes(opReturnValidAddress.ToString()); Transaction transaction = this.transactionBuilder.BuildOpReturnTransaction(this.addressHelper.GetNewSourceChainPubKeyAddress(), opReturnValidAddressBytes); //address 2 will be ignored as not valid for target chain byte[] opReturnInvalidAddressBytes = Encoding.UTF8.GetBytes(this.addressHelper.GetNewSourceChainPubKeyAddress().ToString()); transaction.AddOutput(Money.Zero, new Script(OpcodeType.OP_RETURN, Op.GetPushOp(opReturnInvalidAddressBytes))); //add another output with the same target address, this is not ambiguous transaction.AddOutput(Money.Zero, new Script(OpcodeType.OP_RETURN, Op.GetPushOp(opReturnValidAddressBytes))); //add other random message byte[] randomMessageBytes = Encoding.UTF8.GetBytes("neither hash, nor address"); transaction.AddOutput(Money.Zero, new Script(OpcodeType.OP_RETURN, Op.GetPushOp(randomMessageBytes))); this.opReturnDataReader.TryGetTargetAddress(transaction, out string addressFromOpReturn); addressFromOpReturn.Should().Be(opReturnValidAddress.ToString()); }
public void BuildTransactionUsesGivenChangeAddress() { WalletTransactionHandlerTestContext testContext = SetupWallet(); TransactionBuildContext context = CreateContext(this.Network, testContext.WalletReference, "password", testContext.DestinationKeys.PubKey.ScriptPubKey, new Money(7500), FeeType.Low, 0); var key = new Key(); BitcoinPubKeyAddress address = key.PubKey.GetAddress(this.Network); HdAddress changeAddress = context.ChangeAddress = new HdAddress { Index = 0, HdPath = $"m/44'/0'/0'/0/0", Address = address.ToString(), Pubkey = key.PubKey.ScriptPubKey, ScriptPubKey = address.ScriptPubKey, //Transactions = new List<TransactionData>() }; Transaction transactionResult = testContext.WalletTransactionHandler.BuildTransaction(context); Transaction result = this.Network.CreateTransaction(transactionResult.ToHex()); Assert.Single(result.Inputs); Assert.Equal(testContext.AddressTransaction.Id, result.Inputs[0].PrevOut.Hash); Assert.Equal(2, result.Outputs.Count); TxOut output = result.Outputs[0]; Assert.Equal((testContext.AddressTransaction.Amount - context.TransactionFee - 7500), output.Value); Assert.Equal(changeAddress.ScriptPubKey, output.ScriptPubKey); output = result.Outputs[1]; Assert.Equal(7500, output.Value); Assert.Equal(testContext.DestinationKeys.PubKey.ScriptPubKey, output.ScriptPubKey); Assert.Equal(testContext.AddressTransaction.Amount - context.TransactionFee, result.TotalOut); Assert.NotNull(transactionResult.GetHash()); Assert.Equal(result.GetHash(), transactionResult.GetHash()); }
public void CanParseColoredAddress() { var address = new BitcoinPubKeyAddress("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM"); var colored = address.ToColoredAddress(); Assert.Equal("akB4NBW9UuCmHuepksob6yfZs6naHtRCPNy", colored.ToWif()); Assert.Equal(address.ScriptPubKey, colored.ScriptPubKey); var testAddress = address.ToNetwork(Network.TestNet); var testColored = testAddress.ToColoredAddress(); Assert.Equal(Network.TestNet, testAddress.Network); Assert.Equal(address.Hash, testAddress.Hash); Assert.Equal(colored.ToNetwork(Network.TestNet), testColored); Assert.Equal(testAddress.ScriptPubKey, testColored.ScriptPubKey); Assert.Equal(Network.TestNet, testColored.Network); testColored = new BitcoinColoredAddress("bWqaKUZETiECYgmJNbNZUoanBxnAzoVjCNx"); Assert.Equal(Network.TestNet, testColored.Network); Assert.Equal(colored.ToNetwork(Network.TestNet), testColored); }
//https://en.bitcoin.it/wiki/List_of_address_prefixes public void CanDeduceNetworkInBase58Constructor() { BitcoinAddress addr = new BitcoinPubKeyAddress("17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem"); Assert.Equal(addr.Network, Network.Main); }