Exemple #1
0
        public void LinearDictionaryCoder()
        {
            var testPath = "linearDictionaryUnitTest";

            if (File.Exists(testPath))
            {
                File.Delete(testPath);
            }

            var linearDictionaryCoder = new LinearDictionaryEncoder(testPath, 32, 32);

            var expectedDictionary = new Dictionary <byte[], byte[]>();

            LargeInteger value = 0;

            for (int i = 0; i < 1500; i++)
            {
                var valueBytes = ByteManipulator.BigEndianTruncate(value.GetBytes(), 32);

                var key = CryptographyHelper.Sha3256(valueBytes);

                linearDictionaryCoder.Add(key, valueBytes);
                expectedDictionary.Add(key, valueBytes);

                value = value + 1;
            }

            foreach (var kvp in expectedDictionary)
            {
                var entryValue = linearDictionaryCoder.Get(kvp.Key);
                Assert.IsTrue(ArrayManipulator.Compare(kvp.Value, entryValue));
            }
        }
Exemple #2
0
        public async Task <Block> MineRound(Wallet wallet)
        {
            minedBlock.MinerAddress = wallet.PublicKey;

            var difficultyBytes = minedBlock.Difficulty.GetBytes();

            for (int i = 0; i < hashesPerRound; i++)
            {
                if (stop)
                {
                    break;
                }

                minedBlock.Nonce = nonce.GetBytes();

                numberOfAttempts = numberOfAttempts + 1;

                if (ArrayManipulator.IsGreater(ByteManipulator.BigEndianTruncate(difficultyBytes, 32), minedBlock.GetHash(), difficultyBytes.Length)) //new block found
                {
                    stopWatch.Stop();
                    return(minedBlock);
                }

                nonce = nonce + 1;
            }

            return(null);
        }
Exemple #3
0
        public Block(byte[] rlp)
        {
            var decoded = RLP.Decode(rlp);

            if (decoded.Count == 7 && decoded[1] != null)
            {
                Height     = (int)(decoded[0] != null ? ByteManipulator.GetUInt32(decoded[0]) : 0);
                Timestamp  = ByteManipulator.GetUInt32(decoded[1]);
                Difficulty = new LargeInteger(decoded[2] ?? new byte[32]);
                Nonce      = decoded[3] != null?ByteManipulator.BigEndianTruncate(decoded[3], 32) : new byte[32];

                MinerAddress = decoded[4] != null?ByteManipulator.BigEndianTruncate(decoded[4], 33) : new byte[33];

                PreviousBlockHash = decoded[5] != null?ByteManipulator.BigEndianTruncate(decoded[5], 32) : new byte[32];

                var decodedTransactions = RLP.Decode(decoded[6]);

                Transactions = new List <Transaction>();

                if (decodedTransactions != null)
                {
                    foreach (var rlpTransaction in decodedTransactions)
                    {
                        var tx = new Transaction(rlpTransaction);
                        Transactions.Add(tx);
                    }
                }
            }
            else
            {
                throw new Exception("Invalid block");
            }
        }
Exemple #4
0
        public void Add(byte[] key, byte[] value)
        {
            value = ByteManipulator.BigEndianTruncate(value, DataLength);
            key   = ByteManipulator.BigEndianTruncate(key, KeyLength);

            if (LinearCoder.Count == 0)
            {
                LinearCoder.Push(CreateEntry(key, value));
            }
            else
            {
                int minimum = 0;
                int maximum = LinearCoder.Count - 1;

                while (minimum <= maximum)
                {
                    int middle = (minimum + maximum) / 2;

                    var middleValue = LinearCoder.Read(middle);

                    if (ArrayManipulator.Compare(key, middleValue.Take(key.Length).ToArray()))
                    {
                        throw new Exception("Key already exists");
                    }
                    else if (ArrayManipulator.IsGreater(key, middleValue, KeyLength))
                    {
                        minimum = middle + 1;
                    }
                    else
                    {
                        maximum = middle - 1;
                    }
                }

                var popCount = LinearCoder.Count - minimum;

                if ((maximum >= 0) && ArrayManipulator.IsGreater(LinearCoder.Read(maximum), key, KeyLength))
                {
                    popCount++;
                }

                List <byte[]> popedItems;

                if (popCount != 0)
                {
                    popedItems = LinearCoder.BulkPop(popCount);
                }
                else
                {
                    popedItems = new List <byte[]>();
                }

                popedItems.Insert(0, CreateEntry(key, value));

                LinearCoder.BulkPush(popedItems);
            }
        }
        private void Deserialize(byte[] rlp)
        {
            var data = RLP.Decode(rlp);

            Nonce       = ByteManipulator.GetUInt32(data[0] ?? new byte[] { 0 });
            Ammount     = new LargeInteger(data[1] ?? new byte[] { 0 });
            Fee         = new LargeInteger(data[2] ?? new byte[] { 0 });
            Source      = ByteManipulator.BigEndianTruncate(data[3], 33) ?? new byte[33];
            Destination = ByteManipulator.BigEndianTruncate(data[4], 33) ?? new byte[33];
            Signature   = ByteManipulator.BigEndianTruncate(data[5], 64) ?? new byte[64];
            Network     = data[6] ?? new byte[] { 0 };
        }
Exemple #6
0
        public void ExtendUnitTest()
        {
            var input    = new byte[] { 21, 5, 128, 123, 45, 0, 11 };
            var expected = new byte[] { 128, 123, 45, 0, 11 };

            var actual = ByteManipulator.BigEndianTruncate(input, 5);

            for (int i = 0; i < expected.Length; i++)
            {
                Assert.AreEqual(expected[i], actual[i]);
            }
        }
Exemple #7
0
        public bool ContainsKey(byte[] key)
        {
            key = ByteManipulator.BigEndianTruncate(key, KeyLength);

            if (GetIndex(key) < 0)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Exemple #8
0
        public byte[] Get(byte[] key)
        {
            key = ByteManipulator.BigEndianTruncate(key, KeyLength);

            byte[] ret   = null;
            var    index = GetIndex(key);

            if (index != -1)
            {
                ret = LinearCoder.Read(index);
                ret = ArrayManipulator.SubArray(ret, KeyLength, DataLength);
            }

            return(ret);
        }
Exemple #9
0
        public async Task <Block> MineRound()
        {
            var block = new Block()
            {
                Difficulty        = difficulty,
                Height            = height,
                MinerAddress      = minerAddress,
                PreviousBlockHash = previousBlockHash,
                Timestamp         = timestamp,
                Transactions      = transactions
            };

            var difficultyBytes = difficulty.GetBytes();

            for (int i = 0; i < hashesPerRound; i++)
            {
                block.Nonce = nonce.GetBytes();

                numberOfAttempts = numberOfAttempts + 1;

                if (ArrayManipulator.IsGreater(ByteManipulator.BigEndianTruncate(difficultyBytes, 32), block.GetHash(), difficultyBytes.Length)) //new block found
                {
                    lock (GateKeeper.ChainManagerLock)
                    {
                        _chainManager.ProcessBlocks(new List <Block>()
                        {
                            block
                        });
                    }
                    lock (GateKeeper.TransactionPoolLock)
                    {
                        lock (GateKeeper.BalanceLedgerLock)
                        {
                            _transactionPool.Clean();
                        }
                    }

                    BlockTime = block.Timestamp - lastBlockTimeStamp;

                    return(block);
                }

                nonce = nonce + 1;
            }

            return(null);
        }
        public uint GetTransactionCount(byte[] publicKey)
        {
            publicKey = ByteManipulator.BigEndianTruncate(publicKey, 33);
            var nonceBytes = nonceCoder.Get(publicKey);

            uint ret = 0;

            if (nonceBytes != null)
            {
                ret = ByteManipulator.GetUInt32(nonceBytes) + 1;
            }
            else
            {
                ret = 0;
            }

            return(ret);
        }
Exemple #11
0
        public async void AddContact(string url)
        {
            if (url != null)
            {
                var hostnameBytes = ToBytes(url);

                if (hostnameBytes != null)
                {
                    if (!coder.ContainsKey(ByteManipulator.BigEndianTruncate(hostnameBytes, 128)))
                    {
                        if (await Handshake(url))
                        {
                            coder.Add(hostnameBytes, ByteManipulator.GetBytes((uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds));
                        }
                    }
                }
            }
        }
Exemple #12
0
        byte[] CreateEntry(byte[] key, byte[] value)
        {
            key   = ByteManipulator.BigEndianTruncate(key, KeyLength);
            value = ByteManipulator.BigEndianTruncate(value, DataLength);

            var buffer = new byte[KeyLength + DataLength];

            for (int i = 0; i < key.Length; i++)
            {
                buffer[i] = key[i];
            }

            for (int i = 0; i < value.Length; i++)
            {
                buffer[i + key.Length] = value[i];
            }

            return(buffer);
        }
Exemple #13
0
        public Miner(BalanceLedger balanceLedger, TransactionPool transactionPool, ChainManager chainManager)
        {
            _balanceLedger   = balanceLedger;
            _transactionPool = transactionPool;
            _chainManager    = chainManager;

            var minerAddressBytes = HexConverter.ToBytes(Program.Settings.minerAddr);

            if (minerAddressBytes != null && minerAddressBytes.Length < 34)
            {
                minerAddress = ByteManipulator.BigEndianTruncate(minerAddressBytes, 33);
                Console.WriteLine($"[Miner] Miner initialized with address {HexConverter.ToPrefixString(minerAddress)}");
            }
            else
            {
                Console.WriteLine("[Miner] Warning: Invalid address. Miner initialized with address 0x0");
                minerAddress = new byte[33];
            }
        }
Exemple #14
0
        public void BulkPush(List <byte[]> data)
        {
            var buffer = new byte[data.Count * DataLength];

            int counter = 0;

            foreach (var entry in data)
            {
                var extendedEntry = ByteManipulator.BigEndianTruncate(entry, DataLength);

                for (int i = 0; i < DataLength; i++)
                {
                    buffer[counter++] = extendedEntry[i];
                }
            }

            fileStream.Write(buffer);
            fileStream.Flush();

            ReevaluateProperties();
        }
Exemple #15
0
        public async Task <bool> AddContact(string url)
        {
            var ret = false;

            if (url != null)
            {
                var hostnameBytes = ToBytes(url);

                if ((hostnameBytes != null) && (url != Program.Settings.url))
                {
                    if (!coder.ContainsKey(ByteManipulator.BigEndianTruncate(hostnameBytes, 128)))
                    {
                        if (await Handshake(url))
                        {
                            coder.Add(hostnameBytes, ByteManipulator.GetBytes((uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds));
                            ret = true;
                        }
                    }
                }
            }

            return(ret);
        }
Exemple #16
0
        public void RemoveContact(string url)
        {
            var bytes = ByteManipulator.BigEndianTruncate(Encoding.UTF8.GetBytes(url), 128);

            coder.Remove(bytes);
        }
Exemple #17
0
 public void Remove(byte[] key)
 {
     key = ByteManipulator.BigEndianTruncate(key, KeyLength);
     LinearCoder.Remove(GetIndex(key));
 }
 public Block GetBlock(byte[] hash)
 {
     hash = ByteManipulator.BigEndianTruncate(hash, 33);
     return(main.GetByHash(hash));
 }