public void CreateNewInstance_IsCorrectlyInitialised()
        {
            var parameters = new NetworkParameters(new int[] { 2, 8, 4 });
            var network = new MultilayerNetwork(parameters);

            Assert.That(network.Parameters, Is.SameAs(parameters));
            Assert.That(network.LastLayer, Is.SameAs(network.Layers.Last()));
            //Assert.That(network.Layers.Count(), Is.EqualTo(2));

            network.ForEachLayer(l =>
            {
                l.ForEachNeuron((n, i) =>
                {
                    n.Adjust((w, k) => w * 0.1);

                    return 0d;
                });

                return 1;
            });

            network.PruneInputs(1);

            Assert.That(network.Parameters.InputVectorSize, Is.EqualTo(1));
        }
 public MemoryBlockStore(NetworkParameters @params)
 {
     _blockMap = new Dictionary<Sha256Hash, StoredBlock>();
     // Insert the genesis block.
     var genesisHeader = @params.GenesisBlock.CloneAsHeader();
     var storedGenesis = new StoredBlock(genesisHeader, genesisHeader.GetWork(), 0);
     Put(storedGenesis);
     SetChainHead(storedGenesis);
 }
 public void SetUp()
 {
     _unitTestParams = NetworkParameters.UnitTests();
     _wallet = new Wallet(_unitTestParams);
     _wallet.AddKey(new EcKey());
     _chainBlockStore = new MemoryBlockStore(_unitTestParams);
     _chain = new BlockChain(_unitTestParams, _wallet, _chainBlockStore);
     _coinbaseTo = _wallet.Keychain[0].ToAddress(_unitTestParams);
     _someOtherGuy = new EcKey().ToAddress(_unitTestParams);
 }
 /// <exception cref="BlockStoreException"/>
 public BoundedOverheadBlockStore(NetworkParameters @params, FileInfo file)
 {
     _params = @params;
     try
     {
         Load(file);
     }
     catch (IOException e)
     {
         _log.Error("failed to load block store from file", e);
         CreateNewStore(@params, file);
     }
 }
 // Emulates receiving a valid block that builds on top of the chain.
 public static BlockPair CreateFakeBlock(NetworkParameters @params, IBlockStore blockStore, params Transaction[] transactions)
 {
     var b = MakeTestBlock(@params, blockStore);
     // Coinbase tx was already added.
     foreach (var tx in transactions)
         b.AddTransaction(tx);
     b.Solve();
     var pair = new BlockPair();
     pair.Block = b;
     pair.StoredBlock = blockStore.GetChainHead().Build(b);
     blockStore.Put(pair.StoredBlock);
     blockStore.SetChainHead(pair.StoredBlock);
     return pair;
 }
 public static Transaction CreateFakeTx(NetworkParameters @params, ulong nanocoins, Address to)
 {
     var t = new Transaction(@params);
     var o1 = new TransactionOutput(@params, t, nanocoins, to);
     t.AddOutput(o1);
     // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't
     // matter for our purposes.
     var prevTx = new Transaction(@params);
     var prevOut = new TransactionOutput(@params, prevTx, nanocoins, to);
     prevTx.AddOutput(prevOut);
     // Connect it.
     t.AddInput(prevOut);
     return t;
 }
        public void InitialiseAndTrain_ReturnsErrorGt0(int layer1Size, int layer2Size)
        {
            var parameters = new NetworkParameters(new int[] { 4, layer1Size, layer2Size, 4 });

            var network = new MultilayerNetwork(parameters);

            var bp = new BackPropagationLearning(network);

            var input = ColumnVector1D.Create(0, 0.2, 0.66, 0.28);
            var output = ColumnVector1D.Create(0, 0, 0, 0.999);

            var err = bp.Train(input, output);

            Assert.That(err > 0);
        }
Esempio n. 8
0
 /// <exception cref="BlockStoreException"/>
 public DiskBlockStore(NetworkParameters @params, FileInfo file)
 {
     _params = @params;
     _blockMap = new Dictionary<Sha256Hash, StoredBlock>();
     try
     {
         Load(file);
         if (_stream != null)
         {
             _stream.Dispose();
         }
         _stream = file.Open(FileMode.Append, FileAccess.Write); // Do append.
     }
     catch (IOException e)
     {
         _log.Error("failed to load block store from file", e);
         CreateNewStore(@params, file);
     }
 }
 public SeedPeers(NetworkParameters @params)
 {
     _params = @params;
 }
 /// <exception cref="ProtocolException"/>
 public StoredBlock ToStoredBlock(NetworkParameters @params)
 {
     return new StoredBlock(GetHeader(@params), ChainWork, Height);
 }
 /// <exception cref="BlockStoreException"/>
 private void CreateNewStore(NetworkParameters @params, FileInfo file)
 {
     // Create a new block store if the file wasn't found or anything went wrong whilst reading.
     _blockCache.Clear();
     try
     {
         if (_channel != null)
         {
             _channel.Dispose();
             _channel = null;
         }
         if (file.Exists)
         {
             try
             {
                 file.Delete();
             }
             catch (IOException)
             {
                 throw new BlockStoreException("Could not delete old store in order to recreate it");
             }
         }
         _channel = file.Create(); // Create fresh.
         _channel.Write(_fileFormatVersion);
     }
     catch (IOException e1)
     {
         // We could not load a block store nor could we create a new one!
         throw new BlockStoreException(e1);
     }
     try
     {
         // Set up the genesis block. When we start out fresh, it is by definition the top of the chain.
         var genesis = @params.GenesisBlock.CloneAsHeader();
         var storedGenesis = new StoredBlock(genesis, genesis.GetWork(), 0);
         _chainHead = storedGenesis.Header.Hash;
         _channel.Write(_chainHead.Bytes);
         Put(storedGenesis);
     }
     catch (IOException e)
     {
         throw new BlockStoreException(e);
     }
 }
Esempio n. 12
0
 /// <exception cref="BlockStoreException"/>
 public static Block MakeSolvedTestBlock(NetworkParameters @params, Block prev)
 {
     var b = prev.CreateNextBlock(new EcKey().ToAddress(@params));
     b.Solve();
     return b;
 }
Esempio n. 13
0
        public void GetPeerOne()
        {
            var seedPeers = new SeedPeers(NetworkParameters.ProdNet());

            Assert.That(seedPeers.GetPeer(), Is.Not.Null);
        }
Esempio n. 14
0
 public NeuralNetwork(NetworkParameters param)
     : this(param.Inputs, param.Outputs, param.Layers, param.NeuronsPerLayers, param.Checker)
 {
     MaxDepth = param.MaxDepth;
     BaseLearningRate = param.TrainingRate;
 }
Esempio n. 15
0
 public void Initialize(ECKeyPair key, NetworkParameters networkParameters)
 {
     _key = key;
     _networkParameters = networkParameters;
     Console.WriteLine($"Bitcoin Address: {PubKeyAddress}");
 }
Esempio n. 16
0
 /// <exception cref="ProtocolException"/>
 public Block GetHeader(NetworkParameters @params)
 {
     return(new Block(@params, _blockHeader));
 }
Esempio n. 17
0
 /// <see cref="AMessage(NetworkParameters,byte[],int,uint,bool,bool,int)"/>
 protected AMessage(NetworkParameters parameters, byte[] msg, int offset, bool parseLazy, bool parseRetain, int length) : this(parameters, msg, offset, NetworkParameters.ProtocolVersion, parseLazy, parseRetain, length)
 {
 }
Esempio n. 18
0
 /// <see cref="AMessage(NetworkParameters,byte[],int,uint,bool,bool,int)"/>
 protected AMessage(NetworkParameters parameters, byte[] msg, int offset) : this(parameters, msg, offset, NetworkParameters.ProtocolVersion, false, false, UnknownLength)
 {
 }
Esempio n. 19
0
        public void LayeredNetworkCheck()
        {
            var parameters = new NetworkParameters(3, 1)
            {
                InitialConnectionDensity = 1f
            };
            var tracker =
                new InnovationTracker(NetworkParameters.BiasCount + parameters.SensorCount + parameters.EffectorCount);

            var genome = new Genome(parameters, tracker, false);

            genome.SplitConnection(0);
            genome.SplitConnection(2);
            genome.SplitConnection(genome.NeatChromosome.Single(g => g.SourceId == 5).Id);
            while (genome.VacantConnectionCount > 0)
            {
                genome.AddConnection(Neat.Utils.RandomSource.Next(genome.VacantConnectionCount));
            }

            var network = new RecurrentNetwork();

            void AddConnectionAndCopyWeight(int sourceId, int targetId)
            {
                var weight = genome.NeatChromosome.Single(g => g.SourceId == sourceId && g.TargetId == targetId).Weight;

                network.AddConnection(sourceId, targetId, weight);
            }

            #region Network initialization

            network.AddNeuron(0, 0);
            network.AddNeuron(1, 0);
            network.AddNeuron(2, 0);
            network.AddNeuron(3, 0);
            network.AddNeuron(5, 1);
            network.AddNeuron(6, 1);
            network.AddNeuron(7, 2);
            network.AddNeuron(4, 3);
            for (var i = 0; i < 4; i++)
            {
                for (var j = 4; j < 8; j++)
                {
                    AddConnectionAndCopyWeight(i, j);
                }
            }
            for (var i = 4; i < 8; i++)
            {
                for (var j = 4; j < 8; j++)
                {
                    AddConnectionAndCopyWeight(i, j);
                }
            }

            Assert.Equal(network.ConnectionsCount, genome.NeatChromosome.Count);
            #endregion

            float[] result = null;
            for (var i = 0; i < 5; i++)
            {
                var values = new[]
                {
                    1f,
                    Neat.Utils.RandomSource.Next(),
                    Neat.Utils.RandomSource.Next(),
                    Neat.Utils.RandomSource.Next()
                };

                for (var j = 0; j < 3; j++)
                {
                    genome.Network.Sensors[j] = values[j + 1];
                }

                genome.Network.Activate();

                result = network.Activate(values);
            }

            Assert.Equal(result[0], genome.Network.Effectors[0]);
        }
Esempio n. 20
0
 public CloseChannelTransactionBuilder(LocalChannel channel, NetworkParameters networkParameters)
 {
     _channel           = channel;
     _networkParameters = networkParameters;
 }
Esempio n. 21
0
        public void Save_And_Load()
        {
            var parameters = new NetworkParameters(new int[] { 2, 8, 4 })
            {
                LearningRate = 0.123
            };

            var network = new MultilayerNetwork(parameters);

            {
                int li = 0;

                network.ForEachLayer(l =>
                {
                    li += 10;

                    l.ForEachNeuron((n, i) =>
                    {
                        n.Adjust((w, wi) => wi * li);
                        return 0;
                    }).ToList();
                    return 0;
                }).ToList();
            }

            byte[] serialisedData;

            using (var blobStore = new MemoryStream())
            {
                network.Save(blobStore);

                blobStore.Flush();

                serialisedData = blobStore.ToArray();
            }

            using (var blobStoreRead = new MemoryStream(serialisedData))
            {
                var network2 = MultilayerNetwork.LoadData(blobStoreRead);

                Assert.That(network2.Parameters.LearningRate, Is.EqualTo(0.123));
                Assert.That(network2.Parameters.InputVectorSize, Is.EqualTo(2));
                Assert.That(network2.Parameters.OutputVectorSize, Is.EqualTo(4));
                Assert.That(network2.Layers.Count(), Is.EqualTo(3));

                int li = 0;

                network2.ForEachLayer(l =>
                {
                    li += 10;

                    l.ForEachNeuron((n, i) =>
                    {
                        n.Adjust((w, wi) =>
                        {
                            Assert.That(w == wi * li);
                            return w;
                        });
                        return 0;
                    }).ToList();
                    return 0;
                }).ToList();
            }
        }
Esempio n. 22
0
 /// <exception cref="ProtocolException"/>
 public StoredBlock ToStoredBlock(NetworkParameters @params)
 {
     return(new StoredBlock(GetHeader(@params), ChainWork, Height));
 }
Esempio n. 23
0
 /// <summary>
 /// Supports finding peers through DNS A records.
 /// </summary>
 /// <param name="hostNames">Host names to be examined for seed addresses.</param>
 /// <param name="netParams">Network parameters to be used for port information.</param>
 public DnsDiscovery(string[] hostNames, NetworkParameters netParams)
 {
     _hostNames = hostNames;
     _netParams = netParams;
 }
 // this is needed by the BitcoinSerializer
 public VersionAck(NetworkParameters @params, byte[] payload)
 {
 }
 // this is needed by the BitcoinSerializer
 public VersionAck(NetworkParameters @params, byte[] payload)
 {
 }
Esempio n. 26
0
        static void Main(string[] args)
        {
            #region Configs creation.

            BlockchainStorageManagerParameters managerParameters = new BlockchainStorageManagerParameters()
            {
                BlocksInUnit = 2
            };
            UnitRepositoryParameters firstRepositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain0")
            };
            UnitRepositoryParameters secondRepositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain1")
            };
            WalletManagerParameters walletManagerParameters = new WalletManagerParameters()
            {
                WalletDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "wallets")
            };

            NetworkParameters networkParametersFirst = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), FirstBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8900,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            NetworkParameters networkParametersSecond = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), SecondBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8910,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            BasicMiningFactoryParameters parameters = new BasicMiningFactoryParameters()
            {
                HashLeastUpFactor = 1.25,
                HashMostUpFactor  = 1.75,

                HashLeastDownFactor = 0.25,
                HashMostDownFactor  = 0.75,

                DifficultyLeastUpFactor = 1.25,
                DifficultyMostUpFactor  = 1.75,

                DifficultyLeastDownFactor = 0.25,
                DifficultyMostDownFactor  = 0.75,

                MinDifficulty = Difficulty
            };

            JsonSerializer jsonSerializer = new JsonSerializer()
            {
                Formatting = Formatting.Indented
            };

            using (Stream jsonFile = File.Open(MiningConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, parameters);

            using (Stream jsonFile = File.Open(ManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, managerParameters);

            using (Stream jsonFile = File.Open(FirstRepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, firstRepositoryParameters);

            using (Stream jsonFile = File.Open(SecondRepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, secondRepositoryParameters);

            using (Stream jsonFile = File.Open(WalletManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, walletManagerParameters);

            using (Stream jsonFile = File.Open(FirstNetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersFirst);

            using (Stream jsonFile = File.Open(SecondNetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersSecond);

            JsonBasicMiningFactoryConfig       miningConfig           = new JsonBasicMiningFactoryConfig(MiningConfigPath);
            JsonBlockchainStorageManagerConfig managerConfig          = new JsonBlockchainStorageManagerConfig(ManagerConfigPath);
            JsonUnitRepositoryConfig           firstRepositoryConfig  = new JsonUnitRepositoryConfig(FirstRepositoryConfigPath);
            JsonUnitRepositoryConfig           secondRepositoryConfig = new JsonUnitRepositoryConfig(SecondRepositoryConfigPath);
            JsonWalletManagerConfig            walletManagerConfig    = new JsonWalletManagerConfig(WalletManagerConfigPath);
            JsonNetworkConfig firstNetworkConfig  = new JsonNetworkConfig(FirstNetworkConfigPath);
            JsonNetworkConfig secondNetworkConfig = new JsonNetworkConfig(SecondNetworkConfigPath);

            #endregion

            #region Directory remove.

            removeDirectory(firstRepositoryConfig.DirectoryPath);
            removeDirectory(secondRepositoryConfig.DirectoryPath);
            removeDirectory(walletManagerConfig.WalletDirectoryPath);

            #endregion

            #region Directory creation.

            Directory.CreateDirectory(firstRepositoryParameters.DirectoryPath);
            Directory.CreateDirectory(secondRepositoryParameters.DirectoryPath);
            Directory.CreateDirectory(Path.Combine(firstRepositoryConfig.DirectoryPath, "addressers"));
            Directory.CreateDirectory(Path.Combine(firstRepositoryConfig.DirectoryPath, "units"));
            Directory.CreateDirectory(Path.Combine(secondRepositoryConfig.DirectoryPath, "addressers"));
            Directory.CreateDirectory(Path.Combine(secondRepositoryConfig.DirectoryPath, "units"));
            Directory.CreateDirectory(walletManagerConfig.WalletDirectoryPath);

            #endregion

            #region Initial units.

            // Addressers.
            string firstAddresser0Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "addressers", "addresser0.addr");
            string secondAddresser0Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "addressers", "addresser0.addr");

#if (CREATE_EXTRA_FILE)
            string firstAddresser1Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "addressers", "addresser1.addr");
            string secondAddresser1Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "addressers", "addresser1.addr");
#endif

            File.Create(firstAddresser0Path).Close();
            File.Create(secondAddresser0Path).Close();

#if (CREATE_EXTRA_FILE)
            File.Create(firstAddresser1Path).Close();
            File.Create(secondAddresser1Path).Close();
#endif

            // Units.
            string firstUnit0Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "units", "unit0.unit");
            string secondUnit0Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "units", "unit0.unit");

#if (CREATE_EXTRA_FILE)
            string firstUnit1Path  = Path.Combine(firstRepositoryParameters.DirectoryPath, "units", "unit1.unit");
            string secondUnit1Path = Path.Combine(secondRepositoryParameters.DirectoryPath, "units", "unit1.unit");
#endif

            File.Create(firstUnit0Path).Close();
            File.Create(secondUnit0Path).Close();

#if (CREATE_EXTRA_FILE)
            File.Create(firstUnit1Path).Close();
            File.Create(secondUnit1Path).Close();
#endif

            BlockchainUnit firstUnit0  = new BlockchainUnit(firstUnit0Path, new AddressStorage(firstAddresser0Path));
            BlockchainUnit secondUnit0 = new BlockchainUnit(secondUnit0Path, new AddressStorage(secondAddresser0Path));

            #endregion

            IMiningFactory    miningFactory          = new BasicMiningFactory(miningConfig);
            IHashFactory      hashFactory            = miningFactory.GetMiningHashFactoryById(3);
            IHashFactory      transactionHashFactory = new TransactionHashFactory();
            ISignatureFactory signatureFactory       = new ECDSAFactory();
            IWalletManager    walletManager          = new WalletManager(walletManagerConfig, signatureFactory, transactionHashFactory);

            Wallet firstWallet = walletManager.AddNewWallet();

            #region Initial transactions.

            LinkedList <Transaction> firstInitialList  = new LinkedList <Transaction>();
            LinkedList <Transaction> secondInitialList = new LinkedList <Transaction>();

            Transaction firstInitialTransaction  = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 32, transactionHashFactory);
            Transaction secondInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 19, transactionHashFactory);
            Transaction thirdInitialTransaction  = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 32, transactionHashFactory);
            Transaction fourthInitialTransaction = new Transaction(firstWallet.PublicKey, firstWallet.PublicKey, 19, transactionHashFactory);

            firstInitialTransaction.SignTransaction(firstWallet.Signer);
            secondInitialTransaction.SignTransaction(firstWallet.Signer);
            thirdInitialTransaction.SignTransaction(firstWallet.Signer);
            fourthInitialTransaction.SignTransaction(firstWallet.Signer);

            firstInitialList.AddLast(firstInitialTransaction);
            firstInitialList.AddLast(secondInitialTransaction);
            secondInitialList.AddLast(thirdInitialTransaction);
            secondInitialList.AddLast(fourthInitialTransaction);

            #endregion

            #region Initial blocks.

            IHashFactory miningHashFactory = miningFactory.GetMiningHashFactoryById(3);
            IMiner       miner             = new BasicMiner(3, Difficulty, miningHashFactory);

            Block firstInitialBlock = new Block(firstWallet.PublicKey, new byte[hashFactory.GetDigest().HashLength], firstInitialList, hashFactory);

            miner.MineBlock(firstInitialBlock);
            firstInitialBlock.SignBlock(firstWallet.Signer);

            Block secondInitialBlock = new Block(firstWallet.PublicKey, firstInitialBlock.Hash, secondInitialList, hashFactory);

            miner.MineBlock(secondInitialBlock);
            secondInitialBlock.SignBlock(firstWallet.Signer);

            firstUnit0.AddBlock(firstInitialBlock);
            firstUnit0.AddBlock(secondInitialBlock);
            secondUnit0.AddBlock(firstInitialBlock);
            secondUnit0.AddBlock(secondInitialBlock);

            firstUnit0.Dispose();
            secondUnit0.Dispose();

            #endregion

            UnitRepository firstRepository  = new UnitRepository(firstRepositoryConfig);
            UnitRepository secondRepository = new UnitRepository(secondRepositoryConfig);

            BlockchainStorageManager firstManager  = new BlockchainStorageManager(managerConfig, firstRepository);
            BlockchainStorageManager secondManager = new BlockchainStorageManager(managerConfig, secondRepository);

            Blockchain firstBlockchain  = new Blockchain(firstWallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, firstManager);
            Wallet     secondWallet     = walletManager.AddNewWallet();
            Blockchain secondBlockchain = new Blockchain(secondWallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, secondManager);

            #region Address books creation.

            File.Create(FirstBookPath).Close();
            File.Create(SecondBookPath).Close();

            PeerAddress firstPeer  = new PeerAddress(firstWallet.PublicKey);
            PeerAddress secondPeer = new PeerAddress(secondWallet.PublicKey);

            AddressBook firstPeerAddressBook  = new AddressBook(FirstBookPath);
            AddressBook secondPeerAddressBook = new AddressBook(SecondBookPath);

            firstPeerAddressBook.Add(secondPeer, "ws://" + secondNetworkConfig.PeerHostName + $":{secondNetworkConfig.PeerPort}/simplecoin");
            secondPeerAddressBook.Add(firstPeer, "ws://" + firstNetworkConfig.PeerHostName + $":{firstNetworkConfig.PeerPort}/simplecoin");

            firstPeerAddressBook.SaveOnDrive();
            secondPeerAddressBook.SaveOnDrive();

            #endregion

            #region Network.

            IBroadcaster firstNetwork = new Network(firstBlockchain, firstPeerAddressBook, firstNetworkConfig, firstWallet.Signer);

            IBroadcaster secondNetwork = new Network(secondBlockchain, secondPeerAddressBook, secondNetworkConfig, secondWallet.Signer);

            firstBlockchain.NetworkBroadcaster  = firstNetwork;
            secondBlockchain.NetworkBroadcaster = secondNetwork;

            firstNetwork.Start();
            secondNetwork.Start();

            #endregion

            firstWallet.Blockchain  = firstBlockchain;
            secondWallet.Blockchain = secondBlockchain;

            firstWallet.SendTokens(16, secondWallet.PublicKey);
            firstWallet.SendTokens(8, secondWallet.PublicKey);

            secondBlockchain.ProcessPendingTransactions();

            secondWallet.SendTokens(8, firstWallet.PublicKey);
            firstBlockchain.ProcessPendingTransactions();

            Console.WriteLine("First blockchain:\n");

            foreach (Block block in firstBlockchain)
            {
                Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented));
                Console.WriteLine();
            }

            Console.WriteLine("--------------------------------------------------------------------------------------");

            Console.WriteLine("Second blockchain:\n");

            foreach (Block block in secondBlockchain)
            {
                Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented));
                Console.WriteLine();
            }

            Console.WriteLine("}\n");

            Console.WriteLine(firstBlockchain.IsValid ? "First blockchain is valid" : "First blockchain is invalid");
            Console.WriteLine(firstBlockchain.IsValid ? "Second blockchain is valid" : "Second blockchain is invalid");

            Console.WriteLine($"Cryptocurrency ownership for first wallet: {firstBlockchain.CountBalanceForWallet(firstWallet.PublicKey)}");
            Console.WriteLine($"Cryptocurrency ownership for second wallet: {firstBlockchain.CountBalanceForWallet(secondWallet.PublicKey)}");
        }
Esempio n. 27
0
 public AlertMessage(NetworkParameters netParams, byte[] payloadBytes)
     : base(netParams, payloadBytes, 0)
 {
     Version = 1;
 }
Esempio n. 28
0
        public static void Run(string[] args)
        {
            var testNet    = args.Length > 0 && string.Equals(args[0], "testnet", StringComparison.InvariantCultureIgnoreCase);
            var @params    = testNet ? NetworkParameters.TestNet() : NetworkParameters.ProdNet();
            var filePrefix = testNet ? "pingservice-testnet" : "pingservice-prodnet";

            // Try to read the wallet from storage, create a new one if not possible.
            Wallet wallet;
            var    walletFile = new FileInfo(filePrefix + ".wallet");

            try
            {
                wallet = Wallet.LoadFromFile(walletFile);
            }
            catch (IOException)
            {
                wallet = new Wallet(@params);
                wallet.Keychain.Add(new EcKey());
                wallet.SaveToFile(walletFile);
            }
            // Fetch the first key in the wallet (should be the only key).
            var key = wallet.Keychain[0];

            Console.WriteLine(wallet);

            // Load the block chain, if there is one stored locally.
            Console.WriteLine("Reading block store from disk");
            using (var blockStore = new BoundedOverheadBlockStore(@params, new FileInfo(filePrefix + ".blockchain")))
            {
                // Connect to the localhost node. One minute timeout since we won't try any other peers
                Console.WriteLine("Connecting ...");
                var chain = new BlockChain(@params, wallet, blockStore);

                var peerGroup = new PeerGroup(blockStore, @params, chain);
                peerGroup.AddAddress(new PeerAddress(IPAddress.Loopback));
                peerGroup.Start();

                // We want to know when the balance changes.
                wallet.CoinsReceived +=
                    (sender, e) =>
                {
                    // Running on a peer thread.
                    Debug.Assert(!e.NewBalance.Equals(0));
                    // It's impossible to pick one specific identity that you receive coins from in BitCoin as there
                    // could be inputs from many addresses. So instead we just pick the first and assume they were all
                    // owned by the same person.
                    var input = e.Tx.Inputs[0];
                    var from  = input.FromAddress;
                    var value = e.Tx.GetValueSentToMe(wallet);
                    Console.WriteLine("Received " + Utils.BitcoinValueToFriendlyString(value) + " from " + from);
                    // Now send the coins back!
                    var sendTx = wallet.SendCoins(peerGroup, from, value);
                    Debug.Assert(sendTx != null);     // We should never try to send more coins than we have!
                    Console.WriteLine("Sent coins back! Transaction hash is " + sendTx.HashAsString);
                    wallet.SaveToFile(walletFile);
                };

                peerGroup.DownloadBlockChain();
                Console.WriteLine("Send coins to: " + key.ToAddress(@params));
                Console.WriteLine("Waiting for coins to arrive. Press Ctrl-C to quit.");
                // The PeerGroup thread keeps us alive until something kills the process.
            }
        }
Esempio n. 29
0
 /// <exception cref="BlockStoreException"/>
 public static Block MakeSolvedTestBlock(NetworkParameters @params, IBlockStore blockStore)
 {
     var b = blockStore.GetChainHead().Header.CreateNextBlock(new EcKey().ToAddress(@params));
     b.Solve();
     return b;
 }
Esempio n. 30
0
 public SeedPeers(NetworkParameters networkParams)
 {
     _params = networkParams;
 }
Esempio n. 31
0
 /// <exception cref="BlockStoreException"/>
 public static Block MakeTestBlock(NetworkParameters @params, IBlockStore blockStore)
 {
     return blockStore.GetChainHead().Header.CreateNextBlock(new EcKey().ToAddress(@params));
 }
Esempio n. 32
0
 /// <exception cref="BlockStoreException"/>
 public static Block MakeTestBlock(NetworkParameters networkParams, IBlockStore blockStore)
 {
     return(blockStore.GetChainHead().Header.CreateNextBlock(new EcKey().ToAddress(networkParams)));
 }
 /// <exception cref="ProtocolException"/>
 public Block GetHeader(NetworkParameters @params)
 {
     return new Block(@params, _blockHeader);
 }
Esempio n. 34
0
 /**
  * Deserializes an input message. This is usually part of a transaction message.
  */
 public TransactionInput(NetworkParameters params, Transaction parentTransaction,
                         byte[] payload, int offset) throws ProtocolException
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Status == TrainStatus.Running)
                {
                    Status = TrainStatus.Paused;
                    Save();
                    return;
                }

                if (Thread != null && Thread.IsAlive)
                {
                    Thread.Join(); // Wait for last thread to finish working before starting again.
                }
                Termination termination;
                if (cbTerminationType.Text == "ByValidationSet")
                {
                    termination = Termination.ByValidationSet(DataParser.ValidationSet, ToInt(tbValidateCycle, x => x > 0, "Validation cycle must be > 0"));
                }
                else if (cbTerminationType.Text == "ByIteration")
                {
                    termination = Termination.ByIteration(ToInt(tbIterations, x => x > 0, "Iterations must be > 0"));
                }
                else
                {
                    throw new Exception("Did not recognize termination type: " + cbTerminationType.Text);
                }

                NetworkParameters parameters = new NetworkParameters()
                {
                    InitialWeightInterval = new Tuple <double, double>(ToDouble(tbInitialWeightMin), ToDouble(tbInitialWeightMax)),
                    LearningRate          = ToDouble(tbLearningRate, x => x > 0, "Learning rate must be > 0"),
                    LearningRateDecay     = ToDouble(tbLearningRateDecay),
                    Momentum      = ToDouble(tbMomentum, x => x >= 0 && x < 1, "Momentum must be in [0,1)"),
                    MomentumDecay = ToDouble(tbMomentumDecay)
                };

                string name = ToString(tbName, s => s.Trim() != string.Empty, "Network name cannot be empty.");
                if (Status == TrainStatus.Create && Directory.Exists(name))
                {
                    if (MessageBox.Show("Neural Net folder '" + name + "' already exists. Delete contents?\r\nIf not, use a unique name.", "Error", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        (new DirectoryInfo(name)).Delete(true);
                    }
                    else
                    {
                        return;
                    }
                }


                if (Status == TrainStatus.Create)
                {
                    Network = new Network(
                        name,
                        ToInt(tbInputs, x => x > 0, "Number of input nodes must be > 0"),
                        tbHiddens.Text.Split(new char[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => ToInt(x, tbHiddens, xx => xx > 0, "Number of hidden nodes must be > 0 per layer")).ToList <int>(),
                        ToInt(tbOutputs, x => x > 0, "Number of output nodes must be > 0"),
                        termination,
                        parameters);
                }
                else
                {
                    Network.Termination.Type            = termination.Type;
                    Network.Termination.ValidationSet   = termination.ValidationSet;
                    Network.Termination.ValidateCycle   = termination.ValidateCycle;
                    Network.Termination.TotalIterations = termination.TotalIterations;
                    Network.Parameters = parameters;
                    Network.Name       = name;
                }

                Status = TrainStatus.Running;
                Thread = new Thread(new ThreadStart(DoTrain))
                {
                    IsBackground = true
                };
                Thread.Start();
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error");
            }
        }
Esempio n. 36
0
 public RadioNetworkModel(string name, string networkType, NetworkParameters networkParameters)
 {
     this.NetworkName = name;
     this.NetworkType = networkType;
     this.Parameters  = networkParameters;
 }
Esempio n. 37
0
 /// <exception cref="BlockStoreException"/>
 private void CreateNewStore(NetworkParameters @params, FileInfo file)
 {
     // Create a new block store if the file wasn't found or anything went wrong whilst reading.
     _blockMap.Clear();
     try
     {
         if (_stream != null)
         {
             _stream.Dispose();
         }
         _stream = file.OpenWrite(); // Do not append, create fresh.
         _stream.Write(1); // Version.
     }
     catch (IOException e1)
     {
         // We could not load a block store nor could we create a new one!
         throw new BlockStoreException(e1);
     }
     try
     {
         // Set up the genesis block. When we start out fresh, it is by definition the top of the chain.
         var genesis = @params.GenesisBlock.CloneAsHeader();
         var storedGenesis = new StoredBlock(genesis, genesis.GetWork(), 0);
         _chainHead = storedGenesis.Header.Hash;
         _stream.Write(_chainHead.Bytes);
         Put(storedGenesis);
     }
     catch (IOException e)
     {
         throw new BlockStoreException(e);
     }
 }
Esempio n. 38
0
 /// <summary>
 /// Construct a Script using the given network parameters and a range of the programBytes array.
 /// </summary>
 /// <param name="netParams">       Network parameters. </param>
 /// <param name="programBytes"> Array of program bytes from a transaction. </param>
 /// <param name="offset">       How many bytes into programBytes to start reading from. </param>
 /// <param name="length">       How many bytes to read. </param>
 /// <exception cref="ScriptException"> </exception>
 public Script(NetworkParameters netParams, byte[] programBytes, int offset, int length)
 {
     this.netParams = netParams;
     Parse(programBytes, offset, length);
 }
Esempio n. 39
0
 /// <summary>
 /// Supports finding peers through DNS A records. Community run DNS entry points will be used.
 /// </summary>
 /// <param name="netParams">Network parameters to be used for port information.</param>
 public DnsDiscovery(NetworkParameters netParams)
     : this(DefaultHostNames, netParams)
 {
 }
Esempio n. 40
0
 // Only for internal use
 private Script()
 {
     netParams = null;
 }
        private async Task<IRawClassifierTrainingContext<NetworkParameters>> GetOrCreateContext(DataBatch batch)
        {
            IRawClassifierTrainingContext<NetworkParameters> ctx;

            //lock (_trainingContexts)
            {
                if (!_trainingContexts.TryGetValue(batch.Id, out ctx))
                {
                    var name = batch.PropertyOrDefault("Name", batch.Id);

                    var layerSizes = batch.Properties["LayerSizes"].Split(',').Select(s => int.Parse(s)).ToArray();
                    var networkParams = new NetworkParameters(layerSizes);

                    try
                    {
                        var network = new MultilayerNetwork(networkParams);

                        await _blobStore.RestoreAsync(name, network);

                        _trainingContexts[batch.Id] = ctx = _trainingContextFactory.Create(network);
                    }
                    catch
                    {
                        _trainingContexts[batch.Id] = ctx = _trainingContextFactory.Create(networkParams);
                    }
                }
            }

            return ctx;
        }
 public void Initialize(NetworkParameters networkParameters)
 {
     _networkParameters = networkParameters;
 }
Esempio n. 43
0
        public void SetUp()
        {
            _testNetChainBlockStore = new MemoryBlockStore(_testNet);
            _testNetChain = new BlockChain(_testNet, new Wallet(_testNet), _testNetChainBlockStore);
            _unitTestParams = NetworkParameters.UnitTests();
            _wallet = new Wallet(_unitTestParams);
            _wallet.AddKey(new EcKey());

            ResetBlockStore();
            _chain = new BlockChain(_unitTestParams, _wallet, _blockStore);

            _coinbaseTo = _wallet.Keychain[0].ToAddress(_unitTestParams);
        }
Esempio n. 44
0
 public LightningNode(ECKeyPair lightningKey, ECKeyPair walletKey, NetworkParameters networkParameters)
 {
     LocalKey          = lightningKey;
     NetworkParameters = networkParameters;
     _walletKey        = walletKey;
 }