コード例 #1
0
        public void Initialize()
        {
            _wallet = new DevWallet(new WalletConfig(), LimboLogs.Instance);
            IEthereumEcdsa ethereumEcdsa = new EthereumEcdsa(MainNetSpecProvider.Instance, LimboLogs.Instance);

            _bridge = new PersonalBridge(ethereumEcdsa, _wallet);
        }
コード例 #2
0
        public static void Preload(uint preloadGasAmount, Store store, ExpressConsensusNode node, TextWriter writer, CancellationToken cancellationToken)
        {
            Debug.Assert(preloadGasAmount > 0);

            var wallet = DevWallet.FromExpressWallet(node.Wallet);

            using var system = new NeoSystem(store);

            var generationAmount = Blockchain.GenerationAmount[0];
            var gas          = preloadGasAmount / generationAmount;
            var preloadCount = preloadGasAmount % generationAmount == 0 ? gas : gas + 1;

            writer.WriteLine($"Creating {preloadCount} empty blocks to preload {preloadGasAmount} GAS");
            Random random = new Random();

            for (int i = 1; i <= preloadCount; i++)
            {
                if (i % 100 == 0)
                {
                    writer.WriteLine($"  Creating Block {i}");
                }
                var block       = CreatePreloadBlock(wallet, random);
                var relayResult = system.Blockchain.Ask <RelayResultReason>(block).Result;

                if (relayResult != RelayResultReason.Succeed)
                {
                    throw new Exception($"Preload block {i} failed {relayResult}");
                }
            }

            ClaimPreloadGas(system, wallet, random);

            writer.WriteLine($"Preload complete. {preloadCount * generationAmount} GAS loaded into genesis account.");
        }
コード例 #3
0
        public static INdmBlockchainBridge BuildABridge()
        {
            IDbProvider      memDbProvider    = TestMemDbProvider.Init();
            StateReader      stateReader      = new StateReader(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance);
            StateProvider    stateProvider    = new StateProvider(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance);
            IEthereumEcdsa   ecdsa            = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance);
            ITxPool          txPool           = new TxPool.TxPool(new InMemoryTxStorage(), ecdsa, MainnetSpecProvider.Instance, new TxPoolConfig(), stateProvider, LimboLogs.Instance);
            BlockTree        blockTree        = Build.A.BlockTree().OfChainLength(1).TestObject;
            IWallet          wallet           = new DevWallet(new WalletConfig(), LimboLogs.Instance);
            ReceiptsRecovery receiptsRecovery = new ReceiptsRecovery(ecdsa, MainnetSpecProvider.Instance);
            LogFinder        logFinder        = new LogFinder(blockTree, new InMemoryReceiptStorage(), NullBloomStorage.Instance, LimboLogs.Instance, receiptsRecovery, 1024);

            ReadOnlyTxProcessingEnv processingEnv = new ReadOnlyTxProcessingEnv(
                new ReadOnlyDbProvider(memDbProvider, false),
                new ReadOnlyBlockTree(blockTree),
                MainnetSpecProvider.Instance, LimboLogs.Instance);
            BlockchainBridge blockchainBridge = new BlockchainBridge(
                processingEnv,
                txPool,
                new InMemoryReceiptStorage(),
                NullFilterStore.Instance,
                NullFilterManager.Instance,
                ecdsa,
                Timestamper.Default,
                logFinder,
                false,
                false);

            WalletTxSigner txSigner  = new WalletTxSigner(wallet, ChainId.Mainnet);
            ITxSealer      txSealer0 = new TxSealer(txSigner, Timestamper.Default);
            ITxSealer      txSealer1 = new NonceReservingTxSealer(txSigner, Timestamper.Default, txPool);
            ITxSender      txSender  = new TxPoolSender(txPool, txSealer0, txSealer1);

            return(new NdmBlockchainBridge(blockchainBridge, blockTree, stateReader, txSender));
        }
コード例 #4
0
        protected async Task Prepare()
        {
            _wallet          = new DevWallet(new WalletConfig(), _logManager);
            _feeAccount      = _wallet.GetAccounts()[0];
            _consumerAccount = _wallet.GetAccounts()[1];
            _providerAccount = _wallet.GetAccounts()[2];
            _ndmConfig       = new NdmConfig();

            IReleaseSpec  spec         = _releaseSpec;
            ISpecProvider specProvider = new SingleReleaseSpecProvider(spec, 99);
            StateDb       stateDb      = new StateDb();

            _state = new StateProvider(stateDb, new StateDb(), _logManager);
            StorageProvider storageProvider = new StorageProvider(stateDb, _state, _logManager);

            _state.CreateAccount(_consumerAccount, 1000.Ether());
            _state.CreateAccount(_providerAccount, 1.Ether());
            _state.Commit(spec);
            _state.CommitTree();

            VirtualMachine machine = new VirtualMachine(_state, storageProvider, Substitute.For <IBlockhashProvider>(),
                                                        specProvider, _logManager);
            TransactionProcessor processor = new TransactionProcessor(specProvider, _state, storageProvider, machine, _logManager);

            _bridge = new BlockchainBridge(processor);

            TxReceipt receipt = await DeployContract(Bytes.FromHexString(ContractData.GetInitCode(_feeAccount)));

            ((NdmConfig)_ndmConfig).ContractAddress = receipt.ContractAddress.ToString();
            _contractAddress = receipt.ContractAddress;
            _txPool          = new TxPool.TxPool(new InMemoryTxStorage(), Timestamper.Default,
                                                 new EthereumEcdsa(specProvider.ChainId, _logManager), specProvider, new TxPoolConfig(), _state, _logManager);
            _ndmBridge = new NdmBlockchainBridge(_bridge, _bridge, _bridge, _bridge);
        }
コード例 #5
0
ファイル: Extensions.cs プロジェクト: neo-project/neo-express
 static bool TryGetNEP6Wallet(string path, string password, ProtocolSettings settings, [MaybeNullWhen(false)] out Wallet wallet, [MaybeNullWhen(false)] out UInt160 accountHash)
 {
     try
     {
         var nep6wallet = new Neo.Wallets.NEP6.NEP6Wallet(path, settings);
         using var unlock = nep6wallet.Unlock(password);
         var nep6account = nep6wallet.GetAccounts().SingleOrDefault(a => a.IsDefault)
                           ?? nep6wallet.GetAccounts().SingleOrDefault()
                           ?? throw new InvalidOperationException("Neo-express only supports NEP-6 wallets with a single default account or a single account");
         if (nep6account.IsMultiSigContract())
         {
             throw new Exception("Neo-express doesn't supports multi-sig NEP-6 accounts");
         }
         var keyPair = nep6account.GetKey() ?? throw new Exception("account.GetKey() returned null");
         wallet = new DevWallet(settings, string.Empty);
         var account = wallet.CreateAccount(keyPair.PrivateKey);
         accountHash = account.ScriptHash;
         return(true);
     }
     catch
     {
         wallet      = null;
         accountHash = null;
         return(false);
     }
 }
コード例 #6
0
        protected void Prepare()
        {
            _wallet          = new DevWallet(new WalletConfig(), _logManager);
            _feeAccount      = _wallet.GetAccounts()[0];
            _consumerAccount = _wallet.GetAccounts()[1];
            _providerAccount = _wallet.GetAccounts()[2];
            _ndmConfig       = new NdmConfig();

            IReleaseSpec  spec         = _releaseSpec;
            ISpecProvider specProvider = new SingleReleaseSpecProvider(spec, 99);
            StateDb       stateDb      = new StateDb();

            _state = new StateProvider(stateDb, new StateDb(), _logManager);
            StorageProvider storageProvider = new StorageProvider(stateDb, _state, _logManager);

            _state.CreateAccount(_consumerAccount, 1000.Ether());
            _state.CreateAccount(_providerAccount, 1.Ether());
            _state.Commit(spec);
            _state.CommitTree();

            VirtualMachine       machine   = new VirtualMachine(_state, storageProvider, Substitute.For <IBlockhashProvider>(), _logManager);
            TransactionProcessor processor = new TransactionProcessor(specProvider, _state, storageProvider, machine, _logManager);

            _bridge = new BlockchainBridge(processor, _releaseSpec);

            TxReceipt receipt = DeployContract(Bytes.FromHexString(ContractData.GetInitCode(_feeAccount)));

            _ndmConfig.ContractAddress = receipt.ContractAddress.ToString();
        }
コード例 #7
0
        public void Initialize()
        {
            _wallet = new DevWallet(new WalletConfig(), LimboLogs.Instance);
            IEthereumEcdsa ethereumEcdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance);

            _bridge = new PersonalBridge(ethereumEcdsa, _wallet);
        }
コード例 #8
0
        public async Task RunAsync(IStorageProvider store, ExpressConsensusNode node, bool enableTrace, TextWriter writer, CancellationToken token)
        {
            if (IsNodeRunning(node))
            {
                throw new Exception("Node already running");
            }

            var tcs = new TaskCompletionSource <bool>();

            _ = Task.Run(() =>
            {
                try
                {
                    var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(token);

                    var defaultAccount = node.Wallet.Accounts.Single(a => a.IsDefault);
                    using var mutex    = new Mutex(true, GLOBAL_PREFIX + defaultAccount.ScriptHash);

                    var wallet          = DevWallet.FromExpressWallet(ProtocolSettings, node.Wallet);
                    var multiSigAccount = wallet.GetMultiSigAccounts().Single();

                    var logPlugin             = new Node.LogPlugin(writer);
                    var storageProviderPlugin = new Node.StorageProviderPlugin(store);
                    var appEngineProvider     = enableTrace ? new Node.ApplicationEngineProvider() : null;
                    var dbftPlugin            = new Neo.Consensus.DBFTPlugin(GetConsensusSettings(chain));
                    var persistencePlugin     = new Node.PersistencePlugin(store);

                    using var neoSystem = new Neo.NeoSystem(ProtocolSettings, storageProviderPlugin.Name);
                    _ = neoSystem.ActorSystem.ActorOf(EventWrapper <Blockchain.ApplicationExecuted> .Props(OnApplicationExecuted));
                    var rpcSettings       = GetRpcServerSettings(chain, node);
                    var rpcServer         = new Neo.Plugins.RpcServer(neoSystem, rpcSettings);
                    var expressRpcMethods = new ExpressRpcMethods(neoSystem, store, multiSigAccount.ScriptHash, linkedToken);
                    rpcServer.RegisterMethods(expressRpcMethods);
                    rpcServer.RegisterMethods(persistencePlugin);
                    rpcServer.StartRpcServer();

                    neoSystem.StartNode(new Neo.Network.P2P.ChannelsConfig
                    {
                        Tcp       = new IPEndPoint(IPAddress.Loopback, node.TcpPort),
                        WebSocket = new IPEndPoint(IPAddress.Loopback, node.WebSocketPort),
                    });
                    dbftPlugin.Start(wallet);

                    // DevTracker looks for a string that starts with "Neo express is running" to confirm that the instance has started
                    // Do not remove or re-word this console output:
                    writer.WriteLine($"Neo express is running ({store.GetType().Name})");

                    linkedToken.Token.WaitHandle.WaitOne();
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
                finally
                {
                    tcs.TrySetResult(true);
                }
            });
            await tcs.Task.ConfigureAwait(false);
コード例 #9
0
 public static ExpressWallet CreateWallet(string name)
 {
     using (var wallet = new DevWallet(name))
     {
         var account = wallet.CreateAccount();
         account.IsDefault = true;
         return(wallet.ToExpressWallet());
     }
 }
コード例 #10
0
        public async Task RunAsync(IExpressStore store, ExpressConsensusNode node, uint secondsPerBlock, bool enableTrace, TextWriter writer, CancellationToken token)
        {
            if (IsRunning(node))
            {
                throw new Exception("Node already running");
            }

            chain.InitalizeProtocolSettings(secondsPerBlock);

            await writer.WriteLineAsync(store.GetType().Name).ConfigureAwait(false);

            var tcs = new TaskCompletionSource <bool>();

            _ = Task.Run(() =>
            {
                try
                {
                    var defaultAccount = node.Wallet.Accounts.Single(a => a.IsDefault);
                    using var mutex    = new Mutex(true, GLOBAL_PREFIX + defaultAccount.ScriptHash);

                    var wallet          = DevWallet.FromExpressWallet(node.Wallet);
                    var multiSigAccount = node.Wallet.Accounts.Single(a => a.IsMultiSigContract());

                    var dbftPlugin        = new Neo.Consensus.DBFTPlugin();
                    var logPlugin         = new Node.LogPlugin(writer);
                    var storageProvider   = new Node.ExpressStorageProvider((IStore)store);
                    var appEngineProvider = enableTrace ? new Node.ExpressApplicationEngineProvider() : null;
                    var appLogsPlugin     = new Node.ExpressAppLogsPlugin(store);

                    using var system     = new Neo.NeoSystem(storageProvider.Name);
                    var rpcSettings      = new Neo.Plugins.RpcServerSettings(port: node.RpcPort);
                    var rpcServer        = new Neo.Plugins.RpcServer(system, rpcSettings);
                    var expressRpcServer = new ExpressRpcServer(store, multiSigAccount);
                    rpcServer.RegisterMethods(expressRpcServer);
                    rpcServer.RegisterMethods(appLogsPlugin);
                    rpcServer.StartRpcServer();

                    system.StartNode(new Neo.Network.P2P.ChannelsConfig
                    {
                        Tcp       = new IPEndPoint(IPAddress.Loopback, node.TcpPort),
                        WebSocket = new IPEndPoint(IPAddress.Loopback, node.WebSocketPort),
                    });
                    dbftPlugin.Start(wallet);

                    token.WaitHandle.WaitOne();
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
                finally
                {
                    tcs.TrySetResult(true);
                }
            });
            await tcs.Task.ConfigureAwait(false);
        }
コード例 #11
0
        public static (Wallet wallet, UInt160 accountHash) GetGenesisAccount(this ExpressChain chain, ProtocolSettings settings)
        {
            Debug.Assert(chain.ConsensusNodes != null && chain.ConsensusNodes.Count > 0);

            var wallet  = DevWallet.FromExpressWallet(settings, chain.ConsensusNodes[0].Wallet);
            var account = wallet.GetMultiSigAccounts().Single();

            return(wallet, account.ScriptHash);
        }
コード例 #12
0
        public static ExpressChain CreateBlockchain(int count)
        {
            var wallets = new List <(DevWallet wallet, Neo.Wallets.WalletAccount account)>(count);

            ushort GetPortNumber(int index, ushort portNumber) => (ushort)((49000 + (index * 1000)) + portNumber);

            try
            {
                for (var i = 1; i <= count; i++)
                {
                    var wallet  = new DevWallet($"node{i}");
                    var account = wallet.CreateAccount();
                    account.IsDefault = true;
                    wallets.Add((wallet, account));
                }

                var keys = wallets.Select(t => t.account.GetKey().PublicKey).ToArray();

                var contract = Neo.SmartContract.Contract.CreateMultiSigContract((keys.Length * 2 / 3) + 1, keys);

                foreach (var(wallet, account) in wallets)
                {
                    var multiSigContractAccount = wallet.CreateAccount(contract, account.GetKey());
                    multiSigContractAccount.Label = "MultiSigContract";
                }

                // 49152 is the first port in the "Dynamic and/or Private" range as specified by IANA
                // http://www.iana.org/assignments/port-numbers
                var nodes = new List <ExpressConsensusNode>(count);
                for (var i = 0; i < count; i++)
                {
                    nodes.Add(new ExpressConsensusNode()
                    {
                        TcpPort       = GetPortNumber(i, 333),
                        WebSocketPort = GetPortNumber(i, 334),
                        RpcPort       = GetPortNumber(i, 332),
                        Wallet        = wallets[i].wallet.ToExpressWallet()
                    });
                }

                return(new ExpressChain()
                {
                    Magic = ExpressChain.GenerateMagicValue(),
                    ConsensusNodes = nodes,
                });
            }
            finally
            {
                foreach (var(wallet, _) in wallets)
                {
                    wallet.Dispose();
                }
            }
        }
コード例 #13
0
ファイル: Extensions.cs プロジェクト: neo-project/neo-express
        public static bool TryGetSigningAccount(this ExpressChainManager chainManager, string name, string password, [MaybeNullWhen(false)] out Wallet wallet, [MaybeNullWhen(false)] out UInt160 accountHash)
        {
            if (!string.IsNullOrEmpty(name))
            {
                var settings = chainManager.Chain.GetProtocolSettings();

                if (name.Equals(ExpressChainExtensions.GENESIS, StringComparison.OrdinalIgnoreCase))
                {
                    (wallet, accountHash) = chainManager.Chain.GetGenesisAccount(settings);
                    return(true);
                }

                if (chainManager.Chain.Wallets != null && chainManager.Chain.Wallets.Count > 0)
                {
                    for (int i = 0; i < chainManager.Chain.Wallets.Count; i++)
                    {
                        var expWallet = chainManager.Chain.Wallets[i];
                        if (name.Equals(expWallet.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            wallet      = DevWallet.FromExpressWallet(settings, expWallet);
                            accountHash = wallet.GetAccounts().Single(a => a.IsDefault).ScriptHash;
                            return(true);
                        }
                    }
                }

                for (int i = 0; i < chainManager.Chain.ConsensusNodes.Count; i++)
                {
                    var expWallet = chainManager.Chain.ConsensusNodes[i].Wallet;
                    if (name.Equals(expWallet.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        wallet      = DevWallet.FromExpressWallet(settings, expWallet);
                        accountHash = wallet.GetAccounts().Single(a => !a.Contract.Script.IsMultiSigContract()).ScriptHash;
                        return(true);
                    }
                }

                if (!string.IsNullOrEmpty(password))
                {
                    if (TryGetNEP2Wallet(name, password, settings, out wallet, out accountHash))
                    {
                        return(true);
                    }

                    if (TryGetNEP6Wallet(name, password, settings, out wallet, out accountHash))
                    {
                        return(true);
                    }
                }
            }

            wallet      = null;
            accountHash = null;
            return(false);
コード例 #14
0
        public void Each_account_can_sign_with_simple_key()
        {
            DevWallet wallet = new DevWallet(NullLogManager.Instance);

            for (int i = 1; i <= 10; i++)
            {
                byte[] keyBytes = new byte[32];
                keyBytes[31] = (byte)i;
                PrivateKey key = new PrivateKey(keyBytes);
                Assert.AreEqual(key.Address, wallet.GetAccounts()[i - 1], $"{i}");
            }
        }
コード例 #15
0
        public void Can_sign()
        {
            EthereumSigner signer = new EthereumSigner(new SingleReleaseSpecProvider(LatestRelease.Instance, 99), NullLogManager.Instance);
            DevWallet      wallet = new DevWallet(NullLogManager.Instance);

            for (int i = 1; i <= 10; i++)
            {
                Address   signerAddress = wallet.GetAccounts()[0];
                Signature sig           = wallet.Sign(signerAddress, TestObject.KeccakA);
                Address   recovered     = signer.RecoverAddress(sig, TestObject.KeccakA);
                Assert.AreEqual(signerAddress, recovered, $"{i}");
            }
        }
コード例 #16
0
        public void RestoreCheckpoint(string checkPointArchive, bool force)
        {
            if (chain.ConsensusNodes.Count != 1)
            {
                throw new ArgumentException("Checkpoint restore is only supported on single node express instances", nameof(chain));
            }

            checkPointArchive = ResolveCheckpointFileName(checkPointArchive);
            if (!fileSystem.File.Exists(checkPointArchive))
            {
                throw new Exception($"Checkpoint {checkPointArchive} couldn't be found");
            }

            var node = chain.ConsensusNodes[0];

            if (IsNodeRunning(node))
            {
                var scriptHash = node.Wallet.DefaultAccount?.ScriptHash ?? "<unknown>";
                throw new InvalidOperationException($"node {scriptHash} currently running");
            }

            var checkpointTempPath = fileSystem.GetTempFolder();

            using var folderCleanup = AnonymousDisposable.Create(() =>
            {
                if (fileSystem.Directory.Exists(checkpointTempPath))
                {
                    fileSystem.Directory.Delete(checkpointTempPath, true);
                }
            });

            var nodePath = fileSystem.GetNodePath(node);

            if (fileSystem.Directory.Exists(nodePath))
            {
                if (!force)
                {
                    throw new Exception("You must specify force to restore a checkpoint to an existing blockchain.");
                }

                fileSystem.Directory.Delete(nodePath, true);
            }

            var wallet          = DevWallet.FromExpressWallet(ProtocolSettings, node.Wallet);
            var multiSigAccount = wallet.GetMultiSigAccounts().Single();

            RocksDbUtility.RestoreCheckpoint(checkPointArchive, checkpointTempPath,
                                             ProtocolSettings.Network, ProtocolSettings.AddressVersion, multiSigAccount.ScriptHash);
            fileSystem.Directory.Move(checkpointTempPath, nodePath);
        }
コード例 #17
0
ファイル: OfflineNode.cs プロジェクト: slamj1/neo-express
        public Task <UInt256> ExecuteAsync(ExpressWalletAccount account, Neo.VM.Script script, decimal additionalGas = 0)
        {
            if (disposedValue)
            {
                throw new ObjectDisposedException(nameof(OfflineNode));
            }

            var devAccount = DevWalletAccount.FromExpressWalletAccount(account);
            var devWallet  = new DevWallet(string.Empty, devAccount);
            var signer     = new Signer()
            {
                Account = devAccount.ScriptHash, Scopes = WitnessScope.CalledByEntry
            };
            var tx = devWallet.MakeTransaction(script, devAccount.ScriptHash, new[] { signer });

            if (additionalGas > 0.0m)
            {
                tx.SystemFee += (long)additionalGas.ToBigInteger(NativeContract.GAS.Decimals);
            }
            var context = new ContractParametersContext(tx);

            if (devAccount.IsMultiSigContract())
            {
                var wallets = chain.GetMultiSigWallets(account);

                foreach (var wallet in wallets)
                {
                    if (context.Completed)
                    {
                        break;
                    }

                    wallet.Sign(context);
                }
            }
            else
            {
                devWallet.Sign(context);
            }

            if (!context.Completed)
            {
                throw new Exception();
            }

            tx.Witnesses = context.GetWitnesses();

            return(SubmitTransactionAsync(tx));
        }
コード例 #18
0
        internal static ExpressChain CreateChain(int nodeCount)
        {
            if (nodeCount != 1 && nodeCount != 4 && nodeCount != 7)
            {
                throw new ArgumentException("invalid blockchain node count", nameof(nodeCount));
            }

            var wallets = new List <(DevWallet wallet, Neo.Wallets.WalletAccount account)>(nodeCount);

            for (var i = 1; i <= nodeCount; i++)
            {
                var wallet  = new DevWallet($"node{i}");
                var account = wallet.CreateAccount();
                account.IsDefault = true;
                wallets.Add((wallet, account));
            }

            var keys = wallets.Select(t => t.account.GetKey().PublicKey).ToArray();

            var contract = Neo.SmartContract.Contract.CreateMultiSigContract((keys.Length * 2 / 3) + 1, keys);

            foreach (var(wallet, account) in wallets)
            {
                var multiSigContractAccount = wallet.CreateAccount(contract, account.GetKey());
                multiSigContractAccount.Label = "MultiSigContract";
            }

            // 49152 is the first port in the "Dynamic and/or Private" range as specified by IANA
            // http://www.iana.org/assignments/port-numbers
            var nodes = new List <ExpressConsensusNode>(nodeCount);

            for (var i = 0; i < nodeCount; i++)
            {
                nodes.Add(new ExpressConsensusNode()
                {
                    TcpPort       = GetPortNumber(i, 3),
                    WebSocketPort = GetPortNumber(i, 4),
                    RpcPort       = GetPortNumber(i, 2),
                    Wallet        = wallets[i].wallet.ToExpressWallet()
                });
            }

            return(new ExpressChain()
            {
                Magic = ExpressChain.GenerateMagicValue(),
                ConsensusNodes = nodes,
            });
コード例 #19
0
ファイル: Extensions.cs プロジェクト: neo-project/neo-express
 static bool TryGetNEP2Wallet(string nep2, string password, ProtocolSettings settings, [MaybeNullWhen(false)] out Wallet wallet, [MaybeNullWhen(false)] out UInt160 accountHash)
 {
     try
     {
         var privateKey = Wallet.GetPrivateKeyFromNEP2(nep2, password, settings.AddressVersion);
         wallet = new DevWallet(settings, string.Empty);
         var account = wallet.CreateAccount(privateKey);
         accountHash = account.ScriptHash;
         return(true);
     }
     catch
     {
         wallet      = null;
         accountHash = null;
         return(false);
     }
 }
コード例 #20
0
        public void Setup()
        {
            IConfigManager configManager = Substitute.For <IConfigManager>();

            configManager.GetAsync(null).ReturnsForAnyArgs(new NdmConfig());
            IDataStreamService dataStreamService = Substitute.For <IDataStreamService>();

            _providerService = Substitute.For <IProviderService>();
            ISessionService sessionService = Substitute.For <ISessionService>();

            _ndmNotifier = Substitute.For <INdmNotifier>();
            IConsumerNotifier consumerNotifier = new ConsumerNotifier(_ndmNotifier);

            _wallet          = new DevWallet(new WalletConfig(), LimboLogs.Instance);
            _consumerAddress = _wallet.GetAccounts()[0];
            _accountService  = new AccountService(configManager, dataStreamService, _providerService, sessionService, consumerNotifier, _wallet, "configId", _consumerAddress, LimboLogs.Instance);
        }
コード例 #21
0
        internal static ExpressChain CreateChain(int nodeCount, byte?addressVersion)
        {
            if (nodeCount != 1 && nodeCount != 4 && nodeCount != 7)
            {
                throw new ArgumentException("invalid blockchain node count", nameof(nodeCount));
            }

            var settings = ProtocolSettings.Default with
            {
                Network        = ExpressChain.GenerateNetworkValue(),
                AddressVersion = addressVersion ?? ProtocolSettings.Default.AddressVersion
            };

            var wallets = new List <(DevWallet wallet, WalletAccount account)>(nodeCount);

            for (var i = 1; i <= nodeCount; i++)
            {
                var wallet  = new DevWallet(settings, $"node{i}");
                var account = wallet.CreateAccount();
                account.IsDefault = true;
                wallets.Add((wallet, account));
            }

            var keys     = wallets.Select(t => t.account.GetKey().PublicKey).ToArray();
            var contract = Contract.CreateMultiSigContract((keys.Length * 2 / 3) + 1, keys);

            foreach (var(wallet, account) in wallets)
            {
                var multiSigContractAccount = wallet.CreateAccount(contract, account.GetKey());
                multiSigContractAccount.Label = "Consensus MultiSigContract";
            }

            var nodes = wallets.Select((w, i) => new ExpressConsensusNode
            {
                TcpPort       = GetPortNumber(i, 3),
                WebSocketPort = GetPortNumber(i, 4),
                RpcPort       = GetPortNumber(i, 2),
                Wallet        = w.wallet.ToExpressWallet()
            });

            return(new ExpressChain()
            {
                Network = settings.Network,
                AddressVersion = settings.AddressVersion,
                ConsensusNodes = nodes.ToList(),
            });
コード例 #22
0
        protected async Task Prepare()
        {
            _wallet          = new DevWallet(new WalletConfig(), _logManager);
            _feeAccount      = _wallet.GetAccounts()[0];
            _consumerAccount = _wallet.GetAccounts()[1];
            _providerAccount = _wallet.GetAccounts()[2];
            _ndmConfig       = new NdmConfig();

            IReleaseSpec  spec         = _releaseSpec;
            ISpecProvider specProvider = new SingleReleaseSpecProvider(spec, 99);
            MemDb         stateDb      = new MemDb();
            TrieStore     trieStore    = new TrieStore(stateDb, _logManager);

            _state = new StateProvider(trieStore, new MemDb(), _logManager);
            StorageProvider storageProvider = new StorageProvider(trieStore, _state, _logManager);

            _state.CreateAccount(_consumerAccount, 1000.Ether());
            _state.CreateAccount(_providerAccount, 1.Ether());
            _state.Commit(spec);
            _state.CommitTree(0);

            VirtualMachine machine =
                new VirtualMachine(Substitute.For <IBlockhashProvider>(), specProvider, _logManager);
            TransactionProcessor processor = new TransactionProcessor(specProvider, _state, storageProvider, machine, _logManager);

            _bridge = new BlockchainBridge(processor);

            TxReceipt receipt = await DeployContract(Bytes.FromHexString(ContractData.GetInitCode(_feeAccount)));

            ((NdmConfig)_ndmConfig).ContractAddress = receipt.ContractAddress.ToString();
            _contractAddress = receipt.ContractAddress;
            IBlockTree blockTree = Substitute.For <IBlockTree>();
            Block      block     = Build.A.Block.WithNumber(0).TestObject;

            blockTree.Head.Returns(block);
            TransactionComparerProvider transactionComparerProvider = new TransactionComparerProvider(specProvider, blockTree);

            _txPool = new TxPool.TxPool(
                new EthereumEcdsa(specProvider.ChainId, _logManager),
                new ChainHeadInfoProvider(specProvider, blockTree, _state),
                new TxPoolConfig(),
                new TxValidator(specProvider.ChainId),
                _logManager,
                transactionComparerProvider.GetDefaultComparer());
            _ndmBridge = new NdmBlockchainBridge(_bridge, _bridge, _bridge, _bridge);
        }
コード例 #23
0
        public static bool TryGetAccountHash(this ExpressChain chain, string name, [MaybeNullWhen(false)] out UInt160 accountHash, ProtocolSettings?settings = null)
        {
            settings ??= chain.GetProtocolSettings();

            if (chain.Wallets != null && chain.Wallets.Count > 0)
            {
                for (int i = 0; i < chain.Wallets.Count; i++)
                {
                    if (string.Equals(name, chain.Wallets[i].Name, StringComparison.OrdinalIgnoreCase))
                    {
                        var wallet  = DevWallet.FromExpressWallet(settings, chain.Wallets[i]);
                        var account = wallet.GetAccounts().Single(a => a.IsDefault);
                        accountHash = account.ScriptHash;
                        return(true);
                    }
                }
            }

            Debug.Assert(chain.ConsensusNodes != null && chain.ConsensusNodes.Count > 0);

            for (int i = 0; i < chain.ConsensusNodes.Count; i++)
            {
                var nodeWallet = chain.ConsensusNodes[i].Wallet;
                if (string.Equals(name, nodeWallet.Name, StringComparison.OrdinalIgnoreCase))
                {
                    var wallet  = DevWallet.FromExpressWallet(settings, nodeWallet);
                    var account = wallet.GetAccounts().Single(a => a.IsDefault);
                    accountHash = account.ScriptHash;
                    return(true);
                }
            }

            if (GENESIS.Equals(name, StringComparison.OrdinalIgnoreCase))
            {
                (_, accountHash) = chain.GetGenesisAccount(settings);
                return(true);
            }

            if (TryToScriptHash(name, settings.AddressVersion, out accountHash))
            {
                return(true);
            }

            accountHash = default;
            return(false);
コード例 #24
0
        public static Task RunAsync(Store store, ExpressConsensusNode node, TextWriter writer, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource <bool>();

            Task.Run(() =>
            {
                try
                {
                    var wallet = DevWallet.FromExpressWallet(node.Wallet);
                    using (var system = new NeoSystem(store))
                    {
                        var logPlugin = new LogPlugin(writer);
                        var rpcPlugin = new ExpressNodeRpcPlugin(store);

                        system.StartNode(node.TcpPort, node.WebSocketPort);

                        system.StartConsensus(wallet);
                        system.StartRpc(IPAddress.Loopback, node.RpcPort, wallet);

                        {
                            using var snapshot = Blockchain.Singleton.GetSnapshot();
                            var validators     = snapshot.GetValidators();

                            ;
                        }

                        cancellationToken.WaitHandle.WaitOne();
                    }
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
                finally
                {
                    if (store is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }
                    tcs.TrySetResult(true);
                }
            });

            return(tcs.Task);
        }
コード例 #25
0
        public static INdmBlockchainBridge BuildABridge()
        {
            MemDbProvider   memDbProvider   = new MemDbProvider();
            StateReader     stateReader     = new StateReader(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance);
            StateProvider   stateProvider   = new StateProvider(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance);
            StorageProvider storageProvider = new StorageProvider(memDbProvider.StateDb, stateProvider, LimboLogs.Instance);
            IEthereumEcdsa  ecdsa           = new EthereumEcdsa(MainNetSpecProvider.Instance, LimboLogs.Instance);
            ITxPool         txPool          = new TxPool.TxPool(new InMemoryTxStorage(), Timestamper.Default, ecdsa, MainNetSpecProvider.Instance, new TxPoolConfig(), stateProvider, LimboLogs.Instance);
            // BlockTree blockTree = new BlockTree(memDbProvider.BlocksDb, memDbProvider.HeadersDb, memDbProvider.BlockInfosDb, new ChainLevelInfoRepository(memDbProvider.BlockInfosDb), MainNetSpecProvider.Instance, txPool, NullBloomStorage.Instance, new SyncConfig(), LimboLogs.Instance);
            BlockTree            blockTree      = Build.A.BlockTree().OfChainLength(1).TestObject;
            IWallet              wallet         = new DevWallet(new WalletConfig(), LimboLogs.Instance);
            VirtualMachine       virtualMachine = new VirtualMachine(stateProvider, storageProvider, new BlockhashProvider(blockTree, LimboLogs.Instance), MainNetSpecProvider.Instance, LimboLogs.Instance);
            TransactionProcessor processor      = new TransactionProcessor(MainNetSpecProvider.Instance, stateProvider, storageProvider, virtualMachine, LimboLogs.Instance);

            BlockchainBridge blockchainBridge = new BlockchainBridge(stateReader, stateProvider, storageProvider, blockTree, txPool, new InMemoryReceiptStorage(), NullFilterStore.Instance, NullFilterManager.Instance, wallet, processor, ecdsa, NullBloomStorage.Instance, new ReceiptsRecovery());

            return(new NdmBlockchainBridge(blockchainBridge, txPool));
        }
コード例 #26
0
        public void Can_sign_on_networks_with_chain_id()
        {
            const int      networkId = 40000;
            EthereumSigner signer    = new EthereumSigner(new SingleReleaseSpecProvider(LatestRelease.Instance, networkId), NullLogManager.Instance);
            DevWallet      wallet    = new DevWallet(NullLogManager.Instance);

            for (int i = 1; i <= 10; i++)
            {
                Address     signerAddress = wallet.GetAccounts()[0];
                Transaction tx            = new Transaction();
                tx.SenderAddress = signerAddress;

                wallet.Sign(tx, networkId);
                Address recovered = signer.RecoverAddress(tx, networkId);
                Assert.AreEqual(signerAddress, recovered, $"{i}");
                Assert.AreEqual(networkId, tx.Signature.GetChainId, "chainId");
            }
        }
コード例 #27
0
ファイル: AuRaSealerTests.cs プロジェクト: rlanga/nethermind
        public void Setup()
        {
            _blockTree = Substitute.For <IBlockTree>();
            _headStep  = 10;
            _blockTree.Head.Returns(Build.A.BlockHeader.WithHash(Keccak.Compute("hash")).WithAura(_headStep, Bytes.Empty).TestObject);

            _auRaStepCalculator = Substitute.For <IAuRaStepCalculator>();
            _auRaValidator      = Substitute.For <IAuRaValidator>();
            var wallet = new DevWallet(new WalletConfig(), NullLogManager.Instance);

            _address = wallet.NewAccount(new NetworkCredential(string.Empty, "AAA").SecurePassword);

            _auRaSealer = new AuRaSealer(
                _blockTree,
                _auRaValidator,
                _auRaStepCalculator,
                _address,
                wallet,
                NullLogManager.Instance);
        }
コード例 #28
0
ファイル: OfflineNode.cs プロジェクト: slamj1/neo-express
        Block RunConsensus()
        {
            if (chain.ConsensusNodes.Count == 1)
            {
                var ctx = new ConsensusContext(nodeWallet, Blockchain.Singleton.Store);
                ctx.Reset(0);
                ctx.MakePrepareRequest();
                ctx.MakeCommit();
                return(ctx.CreateBlock());
            }

            // create ConsensusContext for each ConsensusNode
            var contexts = new ConsensusContext[chain.ConsensusNodes.Count];

            for (int x = 0; x < contexts.Length; x++)
            {
                contexts[x] = new ConsensusContext(DevWallet.FromExpressWallet(chain.ConsensusNodes[x].Wallet), Blockchain.Singleton.Store);
                contexts[x].Reset(0);
            }

            // find the primary node for this consensus round
            var primary = contexts.Single(c => c.IsPrimary);
            var prepareRequestPayload = primary.MakePrepareRequest();

            for (int x = 0; x < contexts.Length; x++)
            {
                var context = contexts[x];
                if (context.MyIndex == primary.MyIndex)
                {
                    continue;
                }
                var prepareRequestMessage = context.GetMessage <PrepareRequest>(prepareRequestPayload);
                OnPrepareRequestReceived(context, prepareRequestPayload, prepareRequestMessage);
                var commitPayload = context.MakeCommit();
                var commitMessage = primary.GetMessage <Commit>(commitPayload);
                OnCommitReceived(primary, commitPayload, commitMessage);
            }

            return(primary.CreateBlock());
        }
コード例 #29
0
        public static INdmBlockchainBridge BuildABridge()
        {
            MemDbProvider   memDbProvider   = new MemDbProvider();
            StateReader     stateReader     = new StateReader(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance);
            StateProvider   stateProvider   = new StateProvider(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance);
            StorageProvider storageProvider = new StorageProvider(memDbProvider.StateDb, stateProvider, LimboLogs.Instance);
            IEthereumEcdsa  ecdsa           = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance);
            ITxPool         txPool          = new TxPool.TxPool(new InMemoryTxStorage(), Timestamper.Default, ecdsa, MainnetSpecProvider.Instance, new TxPoolConfig(), stateProvider, LimboLogs.Instance);
            // BlockTree blockTree = new BlockTree(memDbProvider.BlocksDb, memDbProvider.HeadersDb, memDbProvider.BlockInfosDb, new ChainLevelInfoRepository(memDbProvider.BlockInfosDb), MainnetSpecProvider.Instance, txPool, NullBloomStorage.Instance, new SyncConfig(), LimboLogs.Instance);
            BlockTree            blockTree      = Build.A.BlockTree().OfChainLength(1).TestObject;
            IWallet              wallet         = new DevWallet(new WalletConfig(), LimboLogs.Instance);
            VirtualMachine       virtualMachine = new VirtualMachine(stateProvider, storageProvider, new BlockhashProvider(blockTree, LimboLogs.Instance), MainnetSpecProvider.Instance, LimboLogs.Instance);
            TransactionProcessor processor      = new TransactionProcessor(MainnetSpecProvider.Instance, stateProvider, storageProvider, virtualMachine, LimboLogs.Instance);

            ReadOnlyTxProcessingEnv processingEnv = new ReadOnlyTxProcessingEnv(
                new ReadOnlyDbProvider(memDbProvider, false),
                new ReadOnlyBlockTree(blockTree),
                MainnetSpecProvider.Instance, LimboLogs.Instance);
            BlockchainBridge blockchainBridge = new BlockchainBridge(
                processingEnv,
                txPool,
                new InMemoryReceiptStorage(),
                NullFilterStore.Instance,
                NullFilterManager.Instance,
                ecdsa,
                NullBloomStorage.Instance,
                Timestamper.Default,
                LimboLogs.Instance,
                false,
                false);

            WalletTxSigner txSigner  = new WalletTxSigner(wallet, ChainId.Mainnet);
            ITxSealer      txSealer0 = new TxSealer(txSigner, Timestamper.Default);
            ITxSealer      txSealer1 = new NonceReservingTxSealer(txSigner, Timestamper.Default, txPool);
            ITxSender      txSender  = new TxPoolSender(txPool, txSealer0, txSealer1);

            return(new NdmBlockchainBridge(blockchainBridge, blockTree, stateReader, txSender));
        }
コード例 #30
0
        // this method only used in Online/OfflineNode ExecuteAsync
        public static IReadOnlyList <Wallet> GetMultiSigWallets(this ExpressChain chain, ProtocolSettings settings, UInt160 accountHash)
        {
            var builder = ImmutableList.CreateBuilder <Wallet>();

            for (int i = 0; i < chain.ConsensusNodes.Count; i++)
            {
                var wallet = DevWallet.FromExpressWallet(settings, chain.ConsensusNodes[i].Wallet);
                if (wallet.GetAccount(accountHash) != null)
                {
                    builder.Add(wallet);
                }
            }

            for (int i = 0; i < chain.Wallets.Count; i++)
            {
                var wallet = DevWallet.FromExpressWallet(settings, chain.Wallets[i]);
                if (wallet.GetAccount(accountHash) != null)
                {
                    builder.Add(wallet);
                }
            }

            return(builder.ToImmutable());
        }