Commit 02cb8519 authored by Pavel Pavlov's avatar Pavel Pavlov

create DeStream genesis block with transfer to wallet

parent c0331514
......@@ -69,30 +69,35 @@ namespace DeStream.DeStreamD.ForTest
.AddRPC()
.Build();
//(Wallet wallet, Block block, ChainedHeader chainedHeader) result = TestClassHelper.CreateFirstTransaction(nodeSettings, node.WalletManager(), node.NodeService<WalletSettings>(),
// node.NodeService<IWalletFeePolicy>());
//var walletManager = node.WalletManager();
//walletManager.Wallets.Add(result.wallet);
//var wallet0 = node.WalletManager().GetWallet("myWallet61");
/* version with creating wallet */
TestClassHelper.CreateFirstTransaction0("TPPL2wmtxGzP8U6hQsGkRA9yCMsazB33ft", Network.DeStreamTest);
//TNXoZ9paETt1ZiHunwbTrXmBXzeQZGMuyC
TestClassHelper.CreateFirstTransaction0("TNXoZ9paETt1ZiHunwbTrXmBXzeQZGMuyC", Network.DeStreamTest);
(Wallet wallet, Block block, ChainedHeader chainedHeader) result = TestClassHelper.CreateFirstTransaction("TPPL2wmtxGzP8U6hQsGkRA9yCMsazB33ft", nodeSettings, node.WalletManager(), node.NodeService<WalletSettings>(),
node.NodeService<IWalletFeePolicy>());
var walletManager = node.WalletManager();
walletManager.Wallets.Add(result.wallet);
HdAddress addr = result.wallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0);
Key key = result.wallet.GetExtendedPrivateKeyForAddress("password", addr).PrivateKey;
TestClassHelper.CreateTestBlock(node, key);
walletManager.SaveWallets();
//HdAddress addr = result.wallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0);
//Key key = result.wallet.GetExtendedPrivateKeyForAddress("password", addr).PrivateKey;
//TestClassHelper.CreateTestBlock(node, key);
//walletManager.SaveWallets();
//var test = node.WalletManager().GetSpendableTransactionsInWallet("myWallet1").Sum(s => s.Transaction.Amount);
Process currentProcess = Process.GetCurrentProcess();
Console.WriteLine("##############################: " + currentProcess.Id.ToString());
//var test = node.WalletManager().GetSpendableTransactionsInWallet("myWallet1").Sum(s => s.Transaction.Amount);
int qwe0 = 1;
if (node != null)
await node.RunAsync();
int qwe = 1;
//if (node != null)
// await node.RunAsync();
//int qwe = 1;
}
catch (Exception ex)
{
Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.Message);
}
}
......
......@@ -5,8 +5,10 @@ using System.Reflection;
using System.Text;
using System.Threading;
using DeStream.Stratis.Bitcoin.Configuration;
using Microsoft.Extensions.Logging;
using Moq;
using NBitcoin;
using NBitcoin.DataEncoders;
using Stratis.Bitcoin;
using Stratis.Bitcoin.Features.Wallet;
using Stratis.Bitcoin.Features.Wallet.Interfaces;
......@@ -29,27 +31,51 @@ namespace DeStream.DeStreamD.ForTest
{
PubKey addressPubKey = ExtPubKey.Parse(accountExtendedPubKey).Derive(new KeyPath(keyPath)).PubKey;
BitcoinPubKeyAddress address = addressPubKey.GetAddress(wallet.Network);
BitcoinPubKeyAddress address0 = addressPubKey.GetAddress(Network.StratisMain);
return (addressPubKey, address);
}
public static (ConcurrentChain chain, uint256 blockhash, Block block) CreateChainAndCreateFirstBlockWithPaymentToAddress(WalletManager walletManager, Network network, HdAddress address)
public static (ConcurrentChain chain, uint256 blockhash, Block block) CreateChainAndCreateFirstBlock_DeStreamTest(Script address)
{
var chain = new ConcurrentChain(network);
//
var chain = new ConcurrentChain(Network.DeStreamTest);
var block = new Block();
block.Header.HashPrevBlock = chain.Tip.HashBlock;
block.Header.Bits = block.Header.GetWorkRequired(Network.DeStreamTest, chain.Tip);
block.Header.UpdateTime(DateTimeOffset.UtcNow, Network.DeStreamTest, chain.Tip);
//var chain = walletManager.Chain;
var coinbase = new Transaction();
coinbase.AddInput(TxIn.CreateCoinbase(chain.Height + 1));
coinbase.AddOutput(new TxOut(Get6Billion(), address));
//coinbase.AddOutput(new TxOut(Get6Billion(), address.ScriptPubKey));
var block = new Block();
//var block = network.GetGenesis().Header;
block.AddTransaction(coinbase);
block.Header.Nonce = 0;
block.UpdateMerkleRoot();
block.Header.PrecomputeHash();
chain.SetTip(block.Header);
return (chain, block.GetHash(), block);
}
public static (ConcurrentChain chain, uint256 blockhash, Block block) CreateChainAndCreateFirstBlockWithPaymentToAddress(Network network, HdAddress address, string _addr)
{
var chain = new ConcurrentChain(network);
var block = new Block();
block.Header.HashPrevBlock = chain.Tip.HashBlock;
block.Header.Bits = block.Header.GetWorkRequired(network, chain.Tip);
block.Header.UpdateTime(DateTimeOffset.UtcNow, network, chain.Tip);
var coinbase = new Transaction();
coinbase.AddInput(TxIn.CreateCoinbase(chain.Height + 1));
coinbase.AddOutput(new TxOut(Get6Billion(), address.ScriptPubKey));
Script destination = BitcoinAddress.Create(_addr, network).ScriptPubKey;
coinbase.AddOutput(new TxOut(Get6Billion(), destination));
//coinbase.AddOutput(new TxOut(Get6Billion(), address.ScriptPubKey));
block.AddTransaction(coinbase);
block.Header.Nonce = 0;
......@@ -135,12 +161,49 @@ namespace DeStream.DeStreamD.ForTest
return (walletFile, extendedKey);
}
//public static Wallet CreateFirstTransaction(DeStreamNodeSettings nodeSettings, ref DeStreamWalletManager walletManager, WalletSettings walletSettings,
// IWalletFeePolicy _walletFeePolicy)
public static (Wallet wallet, Block block, ChainedHeader chainedHeader) CreateFirstTransaction(DeStreamNodeSettings nodeSettings, WalletManager walletManager, WalletSettings walletSettings,
public static void CreateFirstTransaction0(string _addr, Network network)
{
//var chain = new ConcurrentChain(network);
//var block = new Block();
//block.Header.HashPrevBlock = chain.Tip.HashBlock;
//block.Header.Bits = block.Header.GetWorkRequired(network, chain.Tip);
//block.Header.UpdateTime(DateTimeOffset.UtcNow, network, chain.Tip);
//var coinbase = new Transaction();
//coinbase.AddInput(TxIn.CreateCoinbase(chain.Height + 1));
Script _destination = BitcoinAddress.Create(_addr, network).ScriptPubKey;
//coinbase.AddOutput(new TxOut(Get6Billion(), destination));
//block.AddTransaction(coinbase);
//block.Header.Nonce = 0;
//block.UpdateMerkleRoot();
//block.Header.PrecomputeHash();
//chain.SetTip(block.Header);
//Script scr = new Script("OP_DUP OP_HASH160 93297d1d0f1e3322eb73e7513144dff4d030a8ab OP_EQUALVERIFY OP_CHECKSIG");
Script destination = BitcoinAddress.Create(_addr, network).ScriptPubKey;
var context = new TransactionBuildContext(
new WalletAccountReference("request.WalletName", "request.AccountName"),
new[] { new Recipient { Amount = 7, ScriptPubKey = destination } }.ToList(), "password", "true")
{
TransactionFee = string.IsNullOrEmpty("0") ? null : Money.Parse("0"),
MinConfirmations = 1,
Shuffle = true // We shuffle transaction outputs by default as it's better for anonymity.
};
if (!string.IsNullOrEmpty("medium"))
{
context.FeeType = FeeParser.Parse("medium");
}
Mock<ILoggerFactory> LoggerFactory = new Mock<ILoggerFactory>();
var walletTransactionHandler = new WalletTransactionHandler(LoggerFactory.Object, new Mock<IWalletManager>().Object, new Mock<IWalletFeePolicy>().Object, network);
Transaction transactionResult = walletTransactionHandler.BuildTransaction(context);
string Hex = transactionResult.ToHex();
}
public static (Wallet wallet, Block block, ChainedHeader chainedHeader) CreateFirstTransaction(string _addr, DeStreamNodeSettings nodeSettings, WalletManager walletManager, WalletSettings walletSettings,
IWalletFeePolicy _walletFeePolicy)
{
Wallet wallet = GenerateBlankWalletWithExtKey("myWallet1", "password").wallet;
Wallet wallet = GenerateBlankWalletWithExtKey("myWallet61", "password").wallet;
(ExtKey ExtKey, string ExtPubKey) accountKeys = GenerateAccountKeys(wallet, "password", "m/44'/0'/0'");
(PubKey PubKey, BitcoinPubKeyAddress Address) spendingKeys = GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/0");
(PubKey PubKey, BitcoinPubKeyAddress Address) destinationKeys = GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/1");
......@@ -177,7 +240,80 @@ namespace DeStream.DeStreamD.ForTest
};
//Generate a spendable transaction
(ConcurrentChain chain, uint256 blockhash, Block block) chainInfo = CreateChainAndCreateFirstBlockWithPaymentToAddress(walletManager, wallet.Network, spendingAddress);
(ConcurrentChain chain, uint256 blockhash, Block block) chainInfo = CreateChainAndCreateFirstBlockWithPaymentToAddress(wallet.Network, spendingAddress, _addr);
//(ConcurrentChain chain, uint256 blockhash, Block block) chainInfo = CreateChainAndCreateFirstBlockWithPaymentToAddress(wallet.Network, spendingAddress);
TransactionData spendingTransaction = CreateTransactionDataFromFirstBlock(chainInfo);
spendingAddress.Transactions.Add(spendingTransaction);
// setup a payment to yourself in a new block.
Transaction transaction = SetupValidTransaction(wallet, "password", spendingAddress, destinationKeys.PubKey, changeAddress, new Money(7500), new Money(5000));
Block block = AppendTransactionInNewBlockToChain(chainInfo.chain, transaction);
wallet.AccountsRoot.ElementAt(0).Accounts.Add(new HdAccount
{
Index = 1,
Name = "account1",
HdPath = "m/44'/0'/0'",
ExtendedPubKey = accountKeys.ExtPubKey,
//ExternalAddresses = new List<HdAddress> { spendingAddress, destinationAddress },
ExternalAddresses = new List<HdAddress> { spendingAddress },
//InternalAddresses = new List<HdAddress> { changeAddress }
InternalAddresses = new List<HdAddress> { destinationAddress }
});
var walletFeePolicy = new Mock<IWalletFeePolicy>();
walletFeePolicy.Setup(w => w.GetMinimumFee(258, 50))
.Returns(new Money(5000));
HdAddress spentAddressResult0 = wallet.AccountsRoot.ElementAt(0).Accounts.ElementAt(0).ExternalAddresses.ElementAt(0);
ChainedHeader chainedBlock = chainInfo.chain.GetBlock(block.GetHash());
walletManager.ProcessTransaction(transaction, null, block, false);
walletManager.ProcessBlock(block, chainedBlock);
return (wallet, block, chainedBlock);
}
public static (Wallet wallet, Block block, ChainedHeader chainedHeader) old_CreateFirstTransaction(DeStreamNodeSettings nodeSettings, WalletManager walletManager, WalletSettings walletSettings,
IWalletFeePolicy _walletFeePolicy)
{
Wallet wallet = GenerateBlankWalletWithExtKey("myWallet61", "password").wallet;
(ExtKey ExtKey, string ExtPubKey) accountKeys = GenerateAccountKeys(wallet, "password", "m/44'/0'/0'");
(PubKey PubKey, BitcoinPubKeyAddress Address) spendingKeys = GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/0");
(PubKey PubKey, BitcoinPubKeyAddress Address) destinationKeys = GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/1");
(PubKey PubKey, BitcoinPubKeyAddress Address) changeKeys = GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "1/0");
var spendingAddress = new HdAddress
{
Index = 0,
HdPath = $"m/44'/0'/0'/0/0",
Address = spendingKeys.Address.ToString(),
Pubkey = spendingKeys.PubKey.ScriptPubKey,
ScriptPubKey = spendingKeys.Address.ScriptPubKey,
Transactions = new List<TransactionData>()
};
var destinationAddress = new HdAddress
{
Index = 1,
HdPath = $"m/44'/0'/0'/0/1",
Address = destinationKeys.Address.ToString(),
Pubkey = destinationKeys.PubKey.ScriptPubKey,
ScriptPubKey = destinationKeys.Address.ScriptPubKey,
Transactions = new List<TransactionData>()
};
var changeAddress = new HdAddress
{
Index = 0,
HdPath = $"m/44'/0'/0'/1/0",
Address = changeKeys.Address.ToString(),
Pubkey = changeKeys.PubKey.ScriptPubKey,
ScriptPubKey = changeKeys.Address.ScriptPubKey,
Transactions = new List<TransactionData>()
};
//Generate a spendable transaction
(ConcurrentChain chain, uint256 blockhash, Block block) chainInfo = CreateChainAndCreateFirstBlockWithPaymentToAddress(wallet.Network, spendingAddress, "");
TransactionData spendingTransaction = CreateTransactionDataFromFirstBlock(chainInfo);
spendingAddress.Transactions.Add(spendingTransaction);
......@@ -225,7 +361,7 @@ namespace DeStream.DeStreamD.ForTest
public static Money Get6Billion()
{
return new Money(6000000000);
return new Money(6100000000);
}
public static Block CreateTestBlock(FullNode fullNode, Key key)
......@@ -235,7 +371,6 @@ namespace DeStream.DeStreamD.ForTest
BitcoinSecret dest = new BitcoinSecret(key, fullNode.Network);
var blocks = new List<Block>();
List<Transaction> passedTransactions = null;
uint nonce = 0;
var block = new Block();
......@@ -336,8 +471,45 @@ namespace DeStream.DeStreamD.ForTest
return result;
}
public static Block CreateStratisGenesisBlockTest(ConsensusFactory consensusFactory, uint nTime, uint nNonce, uint nBits, int nVersion, Money genesisReward)
{
string pszTimestamp = "http://www.theonion.com/article/olympics-head-priestess-slits-throat-official-rio--53466";
return CreateStratisGenesisBlockTest(consensusFactory, pszTimestamp, nTime, nNonce, nBits, nVersion, genesisReward);
}
public static Block CreateStratisGenesisBlockTest(ConsensusFactory consensusFactory, string pszTimestamp, uint nTime, uint nNonce, uint nBits, int nVersion, Money genesisReward)
{
Transaction txNew = consensusFactory.CreateTransaction();
txNew.Version = 1;
txNew.Time = nTime;
txNew.AddInput(new TxIn()
{
ScriptSig = new Script(Op.GetPushOp(0), new Op()
{
Code = (OpcodeType)0x1,
PushData = new[] { (byte)42 }
}, Op.GetPushOp(Encoders.ASCII.DecodeData(pszTimestamp)))
});
//txNew.AddOutput(new TxOut()
//{
// Value = genesisReward,
//});
var test = BitcoinAddress.Create("TPPL2wmtxGzP8U6hQsGkRA9yCMsazB33ft");
Script destination = BitcoinAddress.Create("TPPL2wmtxGzP8U6hQsGkRA9yCMsazB33ft", Network.DeStreamTest).ScriptPubKey;
txNew.AddOutput(new TxOut(Get6Billion(), destination));
Block genesis = consensusFactory.CreateBlock();
genesis.Header.BlockTime = Utils.UnixTimeToDateTime(nTime);
genesis.Header.Bits = nBits;
genesis.Header.Nonce = nNonce;
genesis.Header.Version = nVersion;
genesis.Transactions.Add(txNew);
genesis.Header.HashPrevBlock = uint256.Zero;
genesis.UpdateMerkleRoot();
return genesis;
}
}
public static class ReflectionExtensions
{
/// <summary>
......
......@@ -19,6 +19,7 @@ using Stratis.Bitcoin.Utilities.Extensions;
using DeStream.Stratis.Bitcoin.Configuration;
using NBitcoin.Networks;
namespace DeStream.DeStreamD
{
......@@ -34,12 +35,16 @@ namespace DeStream.DeStreamD
try
{
Network network = null;
if (args.Contains("-testnet"))
{
network = Network.DeStreamTest;
}
else
{
network = Network.DeStreamMain;
DeStreamNodeSettings nodeSettings = new DeStreamNodeSettings(network, ProtocolVersion.ALT_PROTOCOL_VERSION, args:args, loadConfiguration:false);
}
DeStreamNodeSettings nodeSettings = new DeStreamNodeSettings(network, ProtocolVersion.ALT_PROTOCOL_VERSION, args: args, loadConfiguration: false);
Console.WriteLine($"current network: {network.Name}");
......
......@@ -2,7 +2,7 @@
"profiles": {
"Stratis.StratisD": {
"commandName": "Project",
"commandLineArgs": "-testnet -debug -loglevel=trace -addnode=192.168.31.142:56849"
"commandLineArgs": "-testnet -debug -loglevel=trace "
},
"Stratis.StratisD Test": {
"commandName": "Project",
......
......@@ -11,6 +11,8 @@ namespace NBitcoin
{
public partial class Network
{
/// <summary> The name of the root folder containing the different Stratis blockchains (StratisMain, StratisTest, StratisRegTest). </summary>
public const string DeStreamRootFolderName = "destream";
......@@ -21,6 +23,10 @@ namespace NBitcoin
public const int StratisDefaultMaxTipAgeInSeconds = 2 * 60 * 60;
public const string WalletAddressDeStreamMain = "TPPL2wmtxGzP8U6hQsGkRA9yCMsazB33ft";
public static Network DeStreamMain => NetworksContainer.GetNetwork("DeStreamMain") ?? NetworksContainer.Register(new DeStreamMain());
public static Network DeStreamTest => NetworksContainer.GetNetwork("DeStreamTest") ?? NetworksContainer.Register(new DeStreamTest());
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using NBitcoin.BouncyCastle.Math;
......@@ -10,10 +11,11 @@ namespace NBitcoin.Networks
{
public class DeStreamTest : Network
{
public IPEndPoint Endpoint { get { return new IPEndPoint(IPAddress.Parse("127.0.0.1"), 50861); } }
const string WalletAddressDeStreamTest = "TPPL2wmtxGzP8U6hQsGkRA9yCMsazB33ft";
public DeStreamTest() //: base()
{
this.DNSSeeds = new List<DNSSeedData>();
this.SeedNodes = new List<NetworkAddress>();
this.Checkpoints = new Dictionary<int, CheckpointInfo>();
......@@ -65,20 +67,6 @@ namespace NBitcoin.Networks
this.Consensus.CoinType = 105;
this.Consensus.DefaultAssumeValid = new uint256("0x98fa6ef0bca5b431f15fd79dc6f879dc45b83ed4b1bbe933a383ef438321958e"); // 372652
Block genesis = CreateStratisGenesisBlock(this.Consensus.ConsensusFactory, 1470467000, 1831645, 0x1e0fffff, 1, Money.Zero);
//Block genesis = CreateStratisGenesisBlock(this.Consensus.ConsensusFactory, 1470467000, 1831645, 0x1e0fffff, 1, Money.Coins(9000000000));
genesis.Header.Time = 1493909211;
genesis.Header.Nonce = 2433759;
genesis.Header.Bits = this.Consensus.PowLimit;
this.Genesis = genesis;
this.Consensus.HashGenesisBlock = genesis.GetHash();
//f79e424c3636eb124bb6d07dcc2266e57575c68b738eb3adae364cd3a6ef2943
Assert(this.Consensus.HashGenesisBlock == uint256.Parse("0x00000e246d7b73b88c9ab55f2e5e94d9e22d471def3df5ea448f5576b1d156b9"));
//Assert(this.Consensus.HashGenesisBlock == uint256.Parse("f79e424c3636eb124bb6d07dcc2266e57575c68b738eb3adae364cd3a6ef2943"));
this.Checkpoints = new Dictionary<int, CheckpointInfo>
{
{ 0, new CheckpointInfo(new uint256("0x00000e246d7b73b88c9ab55f2e5e94d9e22d471def3df5ea448f5576b1d156b9"), new uint256("0x0000000000000000000000000000000000000000000000000000000000000000")) },
......@@ -102,6 +90,15 @@ namespace NBitcoin.Networks
this.Base58Prefixes[(int)Base58Type.ASSET_ID] = new byte[] { 23 };
this.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS] = new byte[] { 0x13 };
Block genesis = CreateDeStreamGenesisBlock(this.Consensus.ConsensusFactory, 1470467000, 1831645, 0x1e0fffff, 1, new Money(6100000000));
genesis.Header.Time = 1493909211;
genesis.Header.Nonce = 2433759;
genesis.Header.Bits = this.Consensus.PowLimit;
this.Genesis = genesis;
this.Consensus.HashGenesisBlock = genesis.GetHash();
Assert(this.Consensus.HashGenesisBlock == uint256.Parse("9588559fe38409c5a5d652e847dd059a105ef8f26015f43a512ef8c8a7962dff"));
var encoder = new Bech32Encoder("bc");
this.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS] = encoder;
this.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS] = encoder;
......@@ -116,9 +113,42 @@ namespace NBitcoin.Networks
new NetworkAddress(IPAddress.Parse("95.128.181.196"), this.DefaultPort), //peak-srv-12
new NetworkAddress(IPAddress.Parse("40.121.9.206"), this.DefaultPort)
});
}
internal Block CreateDeStreamGenesisBlock(ConsensusFactory consensusFactory, uint nTime, uint nNonce, uint nBits, int nVersion, Money genesisReward)
{
string pszTimestamp = "http://www.theonion.com/article/olympics-head-priestess-slits-throat-official-rio--53466";
return CreateDeStreamGenesisBlock(consensusFactory, pszTimestamp, nTime, nNonce, nBits, nVersion, genesisReward);
}
internal Block CreateDeStreamGenesisBlock(ConsensusFactory consensusFactory, string pszTimestamp, uint nTime, uint nNonce, uint nBits, int nVersion, Money genesisReward)
{
Transaction txNew = consensusFactory.CreateTransaction();
txNew.Version = 1;
txNew.Time = nTime;
txNew.AddInput(new TxIn()
{
ScriptSig = new Script(Op.GetPushOp(0), new Op()
{
Code = (OpcodeType)0x1,
PushData = new[] { (byte)42 }
}, Op.GetPushOp(Encoders.ASCII.DecodeData(pszTimestamp)))
});
//Network.Register(network);
//return network;
byte[] prefix = this.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS];
Script destination = (new KeyId(new uint160(Encoders.Base58Check.DecodeData(WalletAddressDeStreamTest).Skip((int)prefix?.ToArray().Length).ToArray()))).ScriptPubKey;
txNew.AddOutput(new TxOut(genesisReward, destination));
Block genesis = consensusFactory.CreateBlock();
genesis.Header.BlockTime = Utils.UnixTimeToDateTime(nTime);
genesis.Header.Bits = nBits;
genesis.Header.Nonce = nNonce;
genesis.Header.Version = nVersion;
genesis.Transactions.Add(txNew);
genesis.Header.HashPrevBlock = uint256.Zero;
genesis.UpdateMerkleRoot();
return genesis;
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment