Exemple #1
0
        internal static void LoadPlugins(BhpSystem system)
        {
            System = system;
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Plugins");

            if (!Directory.Exists(path))
            {
                return;
            }
            foreach (string filename in Directory.EnumerateFiles(path, "*.dll", SearchOption.TopDirectoryOnly))
            {
                Assembly assembly = Assembly.LoadFile(filename);
                foreach (Type type in assembly.ExportedTypes)
                {
                    if (!type.IsSubclassOf(typeof(Plugin)))
                    {
                        continue;
                    }
                    if (type.IsAbstract)
                    {
                        continue;
                    }
                    ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                    if (constructor == null)
                    {
                        continue;
                    }
                    constructor.Invoke(null);
                }
            }
        }
Exemple #2
0
        public static void Test()
        {
            timer.Interval = 5000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
            var system = new BhpSystem(new LevelDBStore(dbPath));

            system.StartNode(10555, 11556);

            Console.WriteLine("block height : " + Blockchain.Singleton.Height);
            Console.WriteLine("Please input any key...");
            Console.ReadKey();

            SignDelegate2 sign = new SignDelegate2(SignWithoutWallet);
            //SignDelegate2 sign = new SignDelegate2(SignWithoutWallet2);

            var tx = CreateGlobalTransfer(sign);

            //var tx = CreateMinnerTransaction(sign);

            system.LocalNode.Tell(new LocalNode.Relay {
                Inventory = tx
            });

            Console.WriteLine("Transaction Replay. press any key...");
            timer.Stop();
            timer.Elapsed -= Timer_Elapsed;
            timer.Dispose();
            Console.ReadKey();
        }
Exemple #3
0
        internal static void LoadPlugins(BhpSystem system)
        {
            System = system;
            if (!Directory.Exists(pluginsPath))
            {
                return;
            }
            foreach (string filename in Directory.EnumerateFiles(pluginsPath, "*.dll", SearchOption.TopDirectoryOnly))
            {
                Assembly assembly = Assembly.LoadFile(filename);
                foreach (Type type in assembly.ExportedTypes)
                {
                    if (!type.IsSubclassOf(typeof(Plugin)))
                    {
                        continue;
                    }
                    if (type.IsAbstract)
                    {
                        continue;
                    }

                    ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                    try
                    {
                        constructor?.Invoke(null);
                    }
                    catch (Exception ex)
                    {
                        Log(nameof(Plugin), LogLevel.Error, $"Failed to initialize plugin: {ex.Message}");
                    }
                }
            }
        }
Exemple #4
0
 public RpcExtension(BhpSystem system, Wallet wallet)
 {
     this.system    = system;
     this.wallet    = wallet;
     walletTimeLock = new WalletTimeLock(ExtensionSettings.Default.WalletConfig.AutoLock);
     Unlocking      = false;
 }
Exemple #5
0
 public RemoteNode(BhpSystem system, object connection, IPEndPoint remote, IPEndPoint local)
     : base(connection, remote, local)
 {
     this.system   = system;
     this.protocol = Context.ActorOf(ProtocolHandler.Props(system));
     LocalNode.Singleton.RemoteNodes.TryAdd(Self, this);
     SendMessage(Message.Create("version", VersionPayload.Create(LocalNode.Singleton.ListenerPort, LocalNode.Nonce, LocalNode.UserAgent, Blockchain.Singleton.Height)));
 }
Exemple #6
0
        public RpcServer(BhpSystem system, Wallet wallet = null, string password = null, bool isAutoLock = false, Fixed8 maxGasInvoke = default(Fixed8))
        {
            this.system       = system;
            this.wallet       = wallet;
            this.maxGasInvoke = maxGasInvoke;

            walletTimeLock = new WalletTimeLock(password, isAutoLock);
        }
Exemple #7
0
 public RpcExtension(BhpSystem system, Wallet wallet, RpcServer rpcServer)
 {
     this.system    = system;
     this.wallet    = wallet;
     walletTimeLock = new WalletTimeLock();
     Unlocking      = false;
     this.rpcServer = rpcServer;
 }
Exemple #8
0
        public RpcServer(BhpSystem system, Wallet wallet = null, Fixed8 maxGasInvoke = default(Fixed8))
        {
            this.system       = system;
            this.Wallet       = wallet;
            this.maxGasInvoke = maxGasInvoke;

            rpcExtension = new RpcExtension(system, wallet, this);
        }
Exemple #9
0
 public LocalNode(BhpSystem system)
 {
     lock (GetType())
     {
         if (singleton != null)
         {
             throw new InvalidOperationException();
         }
         this.system = system;
         singleton   = this;
     }
 }
        protected internal override void OnStart(string[] args)
        {
            bool useRPC = false;

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                case "/rpc":
                case "--rpc":
                case "-r":
                    useRPC = true;
                    break;
                }
            }
            store  = new LevelDBStore(Path.GetFullPath(Settings.Default.Paths.Chain));
            system = new BhpSystem(store);
            system.StartNode(Settings.Default.P2P.Port, Settings.Default.P2P.WsPort);
            if (Settings.Default.UnlockWallet.IsActive)
            {
                try
                {
                    Program.Wallet = OpenWallet(GetIndexer(), Settings.Default.UnlockWallet.Path, Settings.Default.UnlockWallet.Password);
                }
                catch (CryptographicException)
                {
                    Console.WriteLine($"failed to open file \"{Settings.Default.UnlockWallet.Path}\"");
                }
                if (Settings.Default.UnlockWallet.StartConsensus && Program.Wallet != null)
                {
                    OnStartConsensusCommand(null);
                }
            }
            if (useRPC)
            {
                system.StartRpc(IPAddress.Any, Settings.Default.RPC.Port,
                                wallet: Program.Wallet,
                                walletPassword: Settings.Default.UnlockWallet.Password,
                                isAutoLock: Settings.Default.UnlockWallet.AutoLock,
                                sslCert: Settings.Default.RPC.SslCert,
                                password: Settings.Default.RPC.SslCertPassword);


                //BindAddress
                //system.StartRpc(Settings.Default.RPC.BindAddress,
                //    Settings.Default.RPC.Port,
                //    wallet: Program.Wallet,
                //    sslCert: Settings.Default.RPC.SslCert,
                //    password: Settings.Default.RPC.SslCertPassword);
            }
        }
Exemple #11
0
 public Blockchain(BhpSystem system, Store store)
 {
     this.system  = system;
     this.MemPool = new MemoryPool(system, MemoryPoolMaxTransactions);
     this.Store   = store;
     lock (lockObj)
     {
         if (singleton != null)
         {
             throw new InvalidOperationException();
         }
         header_index.AddRange(store.GetHeaderHashList().Find().OrderBy(p => (uint)p.Key).SelectMany(p => p.Value.Hashes));
         stored_header_count += (uint)header_index.Count;
         if (stored_header_count == 0)
         {
             header_index.AddRange(store.GetBlocks().Find().OrderBy(p => p.Value.TrimmedBlock.Index).Select(p => p.Key));
         }
         else
         {
             HashIndexState hashIndex = store.GetHeaderHashIndex().Get();
             if (hashIndex.Index >= stored_header_count)
             {
                 DataCache <UInt256, BlockState> cache = store.GetBlocks();
                 for (UInt256 hash = hashIndex.Hash; hash != header_index[(int)stored_header_count - 1];)
                 {
                     header_index.Insert((int)stored_header_count, hash);
                     hash = cache[hash].TrimmedBlock.PrevHash;
                 }
             }
         }
         if (header_index.Count == 0)
         {
             Persist(GenesisBlock);
         }
         else
         {
             UpdateCurrentSnapshot();
         }
         singleton = this;
     }
 }
        static void Test(string[] args)
        {
            timer.Interval = 15000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
            var system = new BhpSystem(new LevelDBStore(@"D:\BHP\20181018\test-cli\bhp-cli-3\Chain_00F1A2E3"));

            system.StartNode(20555, 20556);

            Console.ReadKey();
            SignDelegate sign = new SignDelegate(SignWithoutWallet);
            var          tx   = CreateGlobalTransfer(sign);

            system.LocalNode.Tell(new LocalNode.Relay {
                Inventory = tx
            });

            Console.WriteLine("The End");
            timer.Stop();
            timer.Elapsed -= Timer_Elapsed;
            timer.Dispose();
            Console.ReadKey();
        }
Exemple #13
0
        static void Main(string[] args)
        {
            BhpSystem system = new BhpSystem(new LevelDBStore(@"db"));

            system.StartNode(10555, 10556);

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 5000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();

            Console.WriteLine(" Please press any key starting...");
            Console.ReadLine();
            Console.WriteLine(" Start Mining...\n");



            Mining(system);
            Console.WriteLine("\n The end of Mining.");
            string line = Console.ReadLine();

            Console.WriteLine(line);
        }
Exemple #14
0
        public static void Test(string[] args)
        {
            timer.Interval = 15000;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
            var system = new BhpSystem(new LevelDBStore(@"D:\BHP-Project\TestBhp\bin\Debug\db"));

            system.StartNode(10555, 10556);

            Console.ReadKey();
            SignDelegate2 sign = new SignDelegate2(SignWithoutWallet);
            var           tx   = CreateGlobalTransfer(sign); // CreateMinnerTransaction(sign);

            system.LocalNode.Tell(new LocalNode.Relay {
                Inventory = tx
            });

            Console.WriteLine("The End. Please press any key...");
            timer.Stop();
            timer.Elapsed -= Timer_Elapsed;
            timer.Dispose();
            Console.ReadKey();
        }
Exemple #15
0
        static void Mining(BhpSystem system)
        {
            Fixed8 amount_netfee   = Fixed8.Zero;
            Fixed8 transaction_fee = Fixed8.Zero;

            ulong nonce = 100156895;

            BRC6Wallet wallet = new BRC6Wallet(new Bhp.Wallets.WalletIndexer(@"walletindex"), @"D:\BHP\Test\t1.json");

            wallet.Unlock("1");
            wallet.WalletTransaction += Wallet_WalletTransaction;

            MiningTransaction miningTransaction = new MiningTransaction();
            MinerTransaction  tx = miningTransaction.MakeMinerTransaction(wallet, 1000, nonce, Fixed8.Zero, Fixed8.Zero);

            Console.WriteLine(tx.ToJson());

            Console.WriteLine("\n Staring Sign......");
            ContractParametersContext context = new ContractParametersContext(tx);

            wallet.Sign(context);
            if (context.Completed)
            {
                Console.WriteLine("\n Sign successfully.");
                context.Verifiable.Witnesses = context.GetWitnesses();
                string hexString = GetTxHashData(context.Verifiable).ToHexString();
                Console.WriteLine($"\n {hexString}");
                system.LocalNode.Tell(new LocalNode.Relay {
                    Inventory = tx
                });

                RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(tx).Result;
                Console.WriteLine("\n relay tx: " + reason);
            }

            Console.ReadLine();
        }
Exemple #16
0
 public void SetSystem(BhpSystem system)
 {
     this.system = system;
 }
Exemple #17
0
        public void TestSetup()
        {
            // protect against external changes on TimeProvider
            TimeProvider.ResetToDefault();

            if (TheBhpSystem == null)
            {
                var mockSnapshot = new Mock <Snapshot>();
                mockSnapshot.SetupGet(p => p.Blocks).Returns(new TestDataCache <UInt256, BlockState>());
                mockSnapshot.SetupGet(p => p.Transactions).Returns(new TestDataCache <UInt256, TransactionState>());
                mockSnapshot.SetupGet(p => p.Accounts).Returns(new TestDataCache <UInt160, AccountState>());
                mockSnapshot.SetupGet(p => p.UnspentCoins).Returns(new TestDataCache <UInt256, UnspentCoinState>());
                mockSnapshot.SetupGet(p => p.SpentCoins).Returns(new TestDataCache <UInt256, SpentCoinState>());
                mockSnapshot.SetupGet(p => p.Validators).Returns(new TestDataCache <ECPoint, ValidatorState>());
                mockSnapshot.SetupGet(p => p.Assets).Returns(new TestDataCache <UInt256, AssetState>());
                mockSnapshot.SetupGet(p => p.Contracts).Returns(new TestDataCache <UInt160, ContractState>());
                mockSnapshot.SetupGet(p => p.Storages).Returns(new TestDataCache <StorageKey, StorageItem>());
                mockSnapshot.SetupGet(p => p.HeaderHashList)
                .Returns(new TestDataCache <UInt32Wrapper, HeaderHashList>());
                mockSnapshot.SetupGet(p => p.ValidatorsCount).Returns(new TestMetaDataCache <ValidatorsCountState>());
                mockSnapshot.SetupGet(p => p.BlockHashIndex).Returns(new TestMetaDataCache <HashIndexState>());
                mockSnapshot.SetupGet(p => p.HeaderHashIndex).Returns(new TestMetaDataCache <HashIndexState>());

                var mockStore = new Mock <Store>();

                var defaultTx = CreateRandomHashInvocationMockTransaction().Object;
                defaultTx.Outputs    = new TransactionOutput[1];
                defaultTx.Outputs[0] = new TransactionOutput
                {
                    AssetId    = Blockchain.UtilityToken.Hash,
                    Value      = new Fixed8(1000000),
                    ScriptHash = UInt160.Zero // doesn't matter for our purposes.
                };

                mockStore.Setup(p => p.GetBlocks()).Returns(new TestDataCache <UInt256, BlockState>());
                mockStore.Setup(p => p.GetTransactions()).Returns(new TestDataCache <UInt256, TransactionState>(
                                                                      new TransactionState
                {
                    BlockIndex  = 1,
                    Transaction = defaultTx
                }));

                mockStore.Setup(p => p.GetAccounts()).Returns(new TestDataCache <UInt160, AccountState>());
                mockStore.Setup(p => p.GetUnspentCoins()).Returns(new TestDataCache <UInt256, UnspentCoinState>());
                mockStore.Setup(p => p.GetSpentCoins()).Returns(new TestDataCache <UInt256, SpentCoinState>());
                mockStore.Setup(p => p.GetValidators()).Returns(new TestDataCache <ECPoint, ValidatorState>());
                mockStore.Setup(p => p.GetAssets()).Returns(new TestDataCache <UInt256, AssetState>());
                mockStore.Setup(p => p.GetContracts()).Returns(new TestDataCache <UInt160, ContractState>());
                mockStore.Setup(p => p.GetStorages()).Returns(new TestDataCache <StorageKey, StorageItem>());
                mockStore.Setup(p => p.GetHeaderHashList()).Returns(new TestDataCache <UInt32Wrapper, HeaderHashList>());
                mockStore.Setup(p => p.GetValidatorsCount()).Returns(new TestMetaDataCache <ValidatorsCountState>());
                mockStore.Setup(p => p.GetBlockHashIndex()).Returns(new TestMetaDataCache <HashIndexState>());
                mockStore.Setup(p => p.GetHeaderHashIndex()).Returns(new TestMetaDataCache <HashIndexState>());
                mockStore.Setup(p => p.GetSnapshot()).Returns(mockSnapshot.Object);

                Console.WriteLine("initialize BhpSystem");
                TheBhpSystem = new BhpSystem(mockStore.Object); // new Mock<BhpSystem>(mockStore.Object);
            }

            // Create a MemoryPool with capacity of 100
            _unit = new MemoryPool(TheBhpSystem, 100);

            // Verify capacity equals the amount specified
            _unit.Capacity.ShouldBeEquivalentTo(100);

            _unit.VerifiedCount.ShouldBeEquivalentTo(0);
            _unit.UnVerifiedCount.ShouldBeEquivalentTo(0);
            _unit.Count.ShouldBeEquivalentTo(0);
        }
Exemple #18
0
 public static Props Props(BhpSystem system, Store store)
 {
     return(Akka.Actor.Props.Create(() => new Blockchain(system, store)).WithMailbox("blockchain-mailbox"));
 }
Exemple #19
0
 public ConsensusService(BhpSystem system, Wallet wallet)
 {
     this.system = system;
     this.wallet = wallet;
 }
Exemple #20
0
 public TaskManager(BhpSystem system)
 {
     this.system = system;
 }
Exemple #21
0
 public static Props Props(BhpSystem system)
 {
     return(Akka.Actor.Props.Create(() => new TaskManager(system)).WithMailbox("task-manager-mailbox"));
 }
Exemple #22
0
 public static Props Props(BhpSystem system)
 {
     return(Akka.Actor.Props.Create(() => new ProtocolHandler(system)).WithMailbox("protocol-handler-mailbox"));
 }
Exemple #23
0
 public ProtocolHandler(BhpSystem system)
 {
     this.system = system;
 }
Exemple #24
0
 public static Props Props(BhpSystem system, Wallet wallet)
 {
     return(Akka.Actor.Props.Create(() => new ConsensusService(system, wallet)).WithMailbox("consensus-service-mailbox"));
 }
Exemple #25
0
 public static Props Props(BhpSystem system)
 {
     return(Akka.Actor.Props.Create(() => new LocalNode(system)));
 }
Exemple #26
0
 public RpcServer(BhpSystem system, Wallet wallet = null)
 {
     this.system = system;
     this.wallet = wallet;
 }
Exemple #27
0
 public Coins(Wallet wallet, BhpSystem system)
 {
     this.current_wallet = wallet;
     this.system         = system;
 }
Exemple #28
0
 internal static Props Props(BhpSystem system, object connection, IPEndPoint remote, IPEndPoint local)
 {
     return(Akka.Actor.Props.Create(() => new RemoteNode(system, connection, remote, local)).WithMailbox("remote-node-mailbox"));
 }
Exemple #29
0
 public MemoryPool(BhpSystem system, int capacity)
 {
     _system  = system;
     Capacity = capacity;
     LoadMaxTxLimitsFromPolicyPlugins();
 }