private void FormDetails_Load(object sender, EventArgs e) { string address = ""; string bitcoinAddress = ""; string hash = ""; string script = ""; string base58Type = ""; Type type = Address.GetType(); using (new HourGlass()) { switch (type.ToString()) { case "NBitcoin.BitcoinScriptAddress": BitcoinScriptAddress bsa = Address as BitcoinScriptAddress; bitcoinAddress = bsa.ToString(); hash = bsa.Hash.ToString(); script = bsa.ScriptPubKey.ToString(); base58Type = bsa.Type.ToString(); break; case "NBitcoin.BitcoinAddress": BitcoinAddress ba = Address as BitcoinAddress; bitcoinAddress = ba.ToString(); hash = ba.Hash.ToString(); script = ba.ScriptPubKey.ToString(); base58Type = ba.Type.ToString(); break; case "NBitcoin.Stealth.BitcoinStealthAddress": BitcoinStealthAddress stealth = Address as BitcoinStealthAddress; bitcoinAddress = stealth.ToString(); hash = stealth.ScanPubKey.Hash.ToString(); script = stealth.ScanPubKey.ScriptPubKey.ToString(); base58Type = stealth.Type.ToString(); break; case "NBitcoin.BitcoinColoredAddress": BitcoinColoredAddress colored = Address as BitcoinColoredAddress; address = colored.ToString(); bitcoinAddress = colored.Address.ToString(); hash = colored.Address.Hash.ToString(); script = colored.ScriptPubKey.ToString(); base58Type = colored.Type.ToString(); break; default: textBoxType.Text = type.ToString(); break; } } textBoxAddress.Text = address; textBoxBitcoinAddress.Text = bitcoinAddress; textBoxPubHash.Text = hash; textBoxScriptPubKey.Text = script; textBoxType.Text = base58Type; textBoxBitcoinAddress.Focus(); }
private void ValidateConversion <T>(TestVector vector, BitcoinAddress address) where T : BitcoinAddress { Assert.NotNull(address); var key = address as T; // Perform some validations Assert.NotNull(key); Assert.Equal(vector.Type, GetAddressType(key)); Assert.Equal(CashFormat.Legacy, GetAddressFormat(key)); Assert.Equal(vector.Legacy, key.ToString()); // Convert to CashAddr format var cashAddrKey = ConvertAddressToCashAddr(key); // And perform some validations Assert.NotNull(cashAddrKey); Assert.Equal(vector.Type, GetAddressType(cashAddrKey)); Assert.Equal(CashFormat.Cashaddr, GetAddressFormat(cashAddrKey)); Assert.Equal(vector.CashAddr, cashAddrKey.ToString()); // Convert back to legacy and validate it var legacyAddrKey = ConvertAddressToLegacy(cashAddrKey); Assert.NotNull(legacyAddrKey); Assert.Equal(vector.Type, GetAddressType(legacyAddrKey)); Assert.Equal(CashFormat.Legacy, GetAddressFormat(legacyAddrKey)); Assert.Equal(vector.Legacy, legacyAddrKey.ToString()); // Raw mode validation var legacyHashBytes = GetHashBytes(legacyAddrKey); var legacyHashString = Encoders.Hex.EncodeData(legacyHashBytes); Assert.Equal(vector.Hash, legacyHashString); var cashAddrHashBytes = GetHashBytes(cashAddrKey); var cashAddrHashString = Encoders.Hex.EncodeData(cashAddrHashBytes); Assert.Equal(vector.Hash, cashAddrHashString); // Try to recreate addresses with hashes switch (address) { case BitcoinPubKeyAddress pubKey: var pubKey2 = new BitcoinPubKeyAddress(pubKey.Hash, pubKey.Network); Assert.Equal(vector.CashAddr, pubKey2.ToString()); break; case BitcoinScriptAddress scriptKey: var scriptKey2 = new BitcoinScriptAddress(scriptKey.Hash, scriptKey.Network); Assert.Equal(vector.CashAddr, scriptKey2.ToString()); break; default: throw new InvalidOperationException(); } }
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 ScriptKeyAddressConversion() { foreach (var vector in TestVectorArray.Where(x => x.Type == Base58Type.SCRIPT_ADDRESS)) { var addr = BitcoinAddress.Create(vector.Legacy, Network.Main); Assert.NotNull(addr); var legacyScriptKey = new BitcoinScriptAddress(vector.Legacy); Assert.Equal(vector.Legacy, legacyScriptKey.ToString()); Assert.Equal(Network.Main, legacyScriptKey.Network); Assert.Equal(vector.Hash, Encoders.Hex.EncodeData(legacyScriptKey.Hash.ToBytes())); var cashAddrScriptKey = new BitcoinScriptAddress(vector.CashAddr); Assert.Equal(vector.CashAddr, cashAddrScriptKey.ToString()); Assert.Equal(Network.Main, cashAddrScriptKey.Network); Assert.Equal(vector.Hash, Encoders.Hex.EncodeData(cashAddrScriptKey.Hash.ToBytes())); ValidateConversion <BitcoinScriptAddress>(vector, addr); } }
public void NewCreateBasicSwap(uint path, params string[] seed) { List <ExtKey> keys = new List <ExtKey>(); Segwit segwit = new Segwit(NBitcoin.Network.TestNet); for (int i = 0; i < seed.Length; i++) { var key = GetKey(path, seed[i]); //var address = segwit.GetP2SHAddress(key); keys.Add(key); //Console.WriteLine(address.ToString()); } NBitcoin.Network _Network = NBitcoin.Network.TestNet; MultiSig multi = new MultiSig(NBitcoin.Network.TestNet); List <PubKey> pubKeys = new List <PubKey>(); for (int i = 0; i < keys.Count; i++) { pubKeys.Add(keys[i].PrivateKey.PubKey); } Script pubKeyScript = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(2, pubKeys.ToArray()); BitcoinAddress address = pubKeyScript.WitHash.GetAddress(_Network); BitcoinScriptAddress p2sh = address.GetScriptAddress(); Console.WriteLine("Send money here: " + p2sh.ToString()); REST.BlockExplorer explorer = new REST.BlockExplorer("https://testnet.blockexplorer.com/"); var response = explorer.GetUnspent(p2sh.ToString()); List <ExplorerUnspent> unspent = response.Convert <List <ExplorerUnspent> >(); List <Transaction> transactions = new List <Transaction>(); foreach (var item in unspent) { ExplorerResponse txResponse = explorer.GetTransaction(item.txid); RawFormat format = RawFormat.Satoshi; var tx = Transaction.Parse(txResponse.data, format, Network.TestNet); transactions.Add(tx); } //Create send transaction. //get redeem script //var redeemScript = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(2, pubKeys.ToArray());// multi.GetRedeemScript(2, keys.ToArray()); Transaction received = transactions[0]; ScriptCoin coin = received.Outputs.AsCoins().First().ToScriptCoin(pubKeyScript.WitHash.ScriptPubKey.Hash.ScriptPubKey); //create transaction: BitcoinAddress destination = BitcoinAddress.Create("2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF"); //the faucet return address TransactionBuilder builder = new TransactionBuilder(); builder.AddCoins(coin); builder.Send(destination, Money.Coins(1.299m)); builder.SendFees(Money.Coins(0.001m)); builder.SetChange(destination); //builder. var unsigned = builder.BuildTransaction(sign: false); var signedA = builder.AddCoins(coin).AddKeys(keys[0].PrivateKey).SignTransaction(unsigned); Transaction signedB = builder.AddCoins(coin).AddKeys(keys[1].PrivateKey).SignTransaction(signedA); Transaction fullySigned = builder.AddCoins(coin).CombineSignatures(signedA, signedB); Console.WriteLine(fullySigned.ToHex()); Console.ReadLine(); }
private CreationCommitmentResult CreateCommitmentTransaction(IWalletAddress wallet, PubKey lockedPubKey, PubKey unlockedPubKey, PubKey revokePubKey, PubKey multisigPairPubKey, IAsset asset, decimal lockedAmount, decimal unlockedAmount, string channelTr) { var multisig = new BitcoinScriptAddress(wallet.MultisigAddress, _connectionParams.Network); var channel = new Transaction(channelTr); var spendCoin = FindCoin(channel, multisig.ToString(), wallet.RedeemScript, lockedAmount + unlockedAmount, asset); if (spendCoin == null) { throw new BackendException($"Not found output in setup channel with amount {lockedAmount + unlockedAmount}", ErrorCode.NoCoinsFound); } TransactionBuilder builder = new TransactionBuilder(); builder.AddCoins(spendCoin); long additionalBtc = 0; var script = CreateOffchainScript(multisigPairPubKey, revokePubKey, lockedPubKey); var unlockedAddress = unlockedPubKey.GetAddress(_connectionParams.Network); var lockedAddress = script.GetScriptAddress(_connectionParams.Network); if (OpenAssetsHelper.IsBitcoin(asset.Id)) { if (unlockedAmount > 0) { builder.Send(unlockedAddress, new Money(unlockedAmount, MoneyUnit.BTC)); } if (lockedAmount > 0) { builder.Send(lockedAddress, new Money(lockedAmount, MoneyUnit.BTC)); } } else { var sendAmount = ((ColoredCoin)spendCoin).Bearer.Amount; var dustAmount = 0L; var assetId = new BitcoinAssetId(asset.BlockChainAssetId).AssetId; if (unlockedAmount > 0) { builder.SendAsset(unlockedAddress, new AssetMoney(assetId, unlockedAmount, asset.MultiplierPower)); dustAmount += new TxOut(Money.Zero, unlockedAddress.ScriptPubKey).GetDustThreshold(builder.StandardTransactionPolicy.MinRelayTxFee); } if (lockedAmount > 0) { builder.Send(lockedAddress, new AssetMoney(assetId, lockedAmount, asset.MultiplierPower)); dustAmount += new TxOut(Money.Zero, lockedAddress.ScriptPubKey).GetDustThreshold(builder.StandardTransactionPolicy.MinRelayTxFee); } additionalBtc = dustAmount - sendAmount; } var fakeFee = new Money(1, MoneyUnit.BTC); var fakeAmount = additionalBtc + fakeFee; builder.SendFees(fakeFee); _transactionBuildHelper.AddFakeInput(builder, fakeAmount); var tr = builder.BuildTransaction(true); _transactionBuildHelper.RemoveFakeInput(tr); return(new CreationCommitmentResult(tr, lockedAddress.ToString(), script.ToHex())); }
public async Task <string> CreateUnsignedChannel(string clientPubKey, string hotWalletPubKey, decimal clientAmount, decimal hubAmount, IAsset asset) { var address = await _multisigService.GetMultisig(clientPubKey); if (address == null) { throw new BackendException($"Client {clientPubKey} is not registered", ErrorCode.BadInputParameter); } var multisig = new BitcoinScriptAddress(address.MultisigAddress, _connectionParams.Network); var clientAddress = new PubKey(clientPubKey).GetAddress(_connectionParams.Network); var hotWalletAddress = new PubKey(hotWalletPubKey).GetAddress(_connectionParams.Network); TransactionBuildContext context = new TransactionBuildContext(_connectionParams.Network, _pregeneratedOutputsQueueFactory); var currentChannel = await _offchainChannelRepository.GetChannel(address.MultisigAddress, asset.Id); if (currentChannel != null && !currentChannel.IsBroadcasted) { throw new BackendException("There is another pending channel setup", ErrorCode.AnotherChannelSetupExists); } return(await context.Build(async() => { var builder = new TransactionBuilder(); var multisigAmount = await SendToMultisig(multisig, multisig, asset, builder, context, -1); decimal clientChannelAmount, hubChannelAmount; if (currentChannel == null) { clientChannelAmount = Math.Max(0, clientAmount - multisigAmount); hubChannelAmount = hubAmount; await SendToMultisig(clientAddress, multisig, asset, builder, context, clientChannelAmount); await SendToMultisig(hotWalletAddress, multisig, asset, builder, context, hubAmount); clientChannelAmount += multisigAmount; } else { clientChannelAmount = Math.Max(0, clientAmount - currentChannel.ClientAmount); hubChannelAmount = Math.Max(0, hubAmount - currentChannel.HubAmount); await SendToMultisig(clientAddress, multisig, asset, builder, context, clientChannelAmount); await SendToMultisig(hotWalletAddress, multisig, asset, builder, context, hubChannelAmount); clientChannelAmount += currentChannel.ClientAmount; hubChannelAmount += currentChannel.HubAmount; } await _transactionBuildHelper.AddFee(builder, context); var tr = builder.BuildTransaction(true); _transactionBuildHelper.AggregateOutputs(tr); var hex = tr.ToHex(); var channel = await _offchainChannelRepository.CreateChannel(multisig.ToString(), asset.Id, hex, clientChannelAmount, hubChannelAmount); await _broadcastedOutputRepository.InsertOutputs(OpenAssetsHelper.OrderBasedColoringOutputs(tr, context) .Select(o => new BroadcastedOutput(o, channel.ChannelId, _connectionParams.Network))); return hex; })); }