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); }
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)); } }
public void BlockSerializationUnitTest() { var wallet = new Wallet(HexConverter.ToBytes("0x03b28e661bd1aeae3919fd83706f969c5cde6994b161089ce96306f34cb87322")); var sender = new Wallet(); var recipient = new Wallet(); var expected = new Block() { Difficulty = new LargeInteger("10000000000000"), Height = 256, MinerAddress = wallet.PublicKey, Nonce = new byte[] { 1, 0 }, Timestamp = 65464, PreviousBlockHash = new byte[32], Transactions = new List <Transaction>() { ChainManagerUnitTests.CreateTransaction(sender, recipient, 1337, 0), ChainManagerUnitTests.CreateTransaction(recipient, sender, 9000, 0) } }; var bytes = expected.Serialize(); var actual = new Block(bytes); Assert.IsTrue(ArrayManipulator.Compare(bytes, actual.Serialize())); }
public void SerialCoderUnitTest() { string path = "serialCoderTest"; if (File.Exists(path)) { File.Delete(path); } var serialCoder = new SerialEncoder(path, 2); var expected = new byte[][] { new byte[42], new byte[253], new byte[1250], new byte[8710], new byte[25] }; for (int i = 0; i < expected.Length; i++) { for (int j = 0; j < expected[i].Length; j++) { expected[i][j] = (byte)(i + 40); //test data } } serialCoder.Replace(expected); var actual = serialCoder.ReadDataByIndex(); for (int i = 0; i < expected.Length; i++) { Assert.IsTrue(ArrayManipulator.Compare(expected[i], actual[i])); } serialCoder.RemoveByIndex(2); serialCoder.RemoveByIndex(3); actual = serialCoder.ReadDataByIndex(); Assert.IsTrue(actual[2].Length == 8710); var value = serialCoder.ReadByIndex(1); for (int i = 0; i < value.Length; i++) { value[i] += 10; } serialCoder.ChangeValueByIndex(1, value); var actualValue = serialCoder.ReadByIndex(1); Assert.IsTrue(ArrayManipulator.Compare(actualValue, value)); }
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); } }
public void LittleEndianByteCompareUnitTest() { var inputA = new byte[] { 127, 56, 212, 36 }; var inputB = new byte[] { 127, 56, 14, 36 }; var actual = ArrayManipulator.IsGreater(inputA, inputB, inputA.Length); Assert.IsTrue(actual); }
public void ReverseTest() { var _arrayManipulator = new ArrayManipulator(); int[] input = new int[] { 1, 2, 3, 4, 5 }; int[] expectedResult = new int[] { 5, 4, 3, 2, 1 }; int[] actualResult = _arrayManipulator.Reverse(input); CollectionAssert.AreEqual(actualResult, expectedResult); }
//[Fact] public void Should_Sum_Array() { var countToTenInitial = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var sumExpected = 55; var arrayManipulator = new ArrayManipulator(); var sumActual = arrayManipulator.Sum(countToTenInitial); Assert.Equal(sumExpected, sumActual); }
public void DeletePartTest() { var _arrayManipulator = new ArrayManipulator(); int position = 3; int[] input = new int[] { 1, 2, 3, 4, 5 }; int[] expectedResult = new int[] { 1, 2, 4, 5 }; int[] actualResult = _arrayManipulator.DeletePart(position, input); CollectionAssert.AreEqual(actualResult, expectedResult); }
public bool Verify(Block previousBlock) { var ret = false; var single = SingleVerify(); var hash = ArrayManipulator.Compare(previousBlock.GetHash(), PreviousBlockHash); var height = (Height - previousBlock.Height) == 1; var timestamp = Timestamp >= previousBlock.Timestamp; ret = hash && height && single && timestamp; return(ret); }
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); }
//[Fact] public void Should_Square_Each_Array_Index() { var countToTenArrayInitial = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var countToTenSquaredExpected = new[] { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }; var arrayManipulator = new ArrayManipulator(countToTenArrayInitial); var countTenSquared = arrayManipulator.Square(); Assert.Equal(countToTenSquaredExpected.Length, countTenSquared.Length); for (var i = 0; i < countToTenSquaredExpected.Length; i++) { Assert.Equal(countToTenSquaredExpected[i], countTenSquared[i]); } }
//[Fact] public void Should_Append_To_Array() { var countToTenArrayInitial = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var countToTendAppended = new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; var arrayManipulator = new ArrayManipulator(countToTenArrayInitial); var countToTenArrayResult = arrayManipulator.Append(11); Assert.Equal(countToTendAppended.Length, countToTenArrayResult.Length); for (var i = 0; i < countToTenArrayResult.Length; i++) { Assert.Equal(countToTendAppended[i], countToTenArrayResult[i]); } }
//[Fact] public void Should_Remove_Specified_Index_From_Array() { var countToTenArrayInitial = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var countToTenRemovedExpected = new[] { 1, 2, 3, 4, 6, 7, 8, 9, 10 }; var arrayManipulator = new ArrayManipulator(countToTenArrayInitial); var countToTenRemoved = arrayManipulator.Remove(4); Assert.Equal(countToTenRemovedExpected.Length, countToTenRemoved.Length); for (var i = 0; i < countToTenRemovedExpected.Length; i++) { Assert.Equal(countToTenRemovedExpected[i], countToTenRemoved[i]); } }
//[Fact] public void Should_Truncate_Array() { var countToTenArrayInitial = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var conuntToTenTruncatedExpected = new int[] { 1, 2, 3, 4, 5, 6, 7 }; var arrayManipulator = new ArrayManipulator(countToTenArrayInitial); var conuntToTenTruncated = arrayManipulator.Truncate(3); Assert.Equal(conuntToTenTruncated.Length, conuntToTenTruncatedExpected.Length); for (var i = 0; i < conuntToTenTruncated.Length; i++) { Assert.Equal(conuntToTenTruncated[i], conuntToTenTruncatedExpected[i]); } }
//[Fact] public void Should_Prepend_TO_Array() { var countToTenArrayInitial = new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var countToTenPrependedExpected = new [] { 42, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var arrayManipulator = new ArrayManipulator(countToTenArrayInitial); var countToTenPrepended = arrayManipulator.Prepend(42); Assert.Equal(countToTenPrepended.Length, countToTenPrepended.Length); for (var i = 0; i < countToTenPrepended.Length; i++) { Assert.Equal(countToTenPrepended[i], countToTenPrependedExpected[i]); } }
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); }
private int GetIndex(byte[] key) { if (LinearCoder.Count == 1) { var value = LinearCoder.Read(0); if (!ArrayManipulator.Compare(key, value)) { return(-1); } return(0); } else if (key != null && key.Length == KeyLength) { 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())) { return(middle); } else if (ArrayManipulator.IsGreater(key, middleValue, KeyLength)) { minimum = middle + 1; } else { maximum = middle - 1; } } return(-1); } else { throw new Exception("Invalid key format"); } }
//[Fact] public void Should_Concatenate_Arrays() { var countToTenInitialLeft = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var countToTenInitialRight = new[] { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 }; var countToTenConcatenatedExpected = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 }; var arrayManipulator = new ArrayManipulator(); var countToTenConcatenated = arrayManipulator.Concat(countToTenInitialLeft, countToTenInitialRight); Assert.Equal(countToTenConcatenatedExpected.Length, countToTenInitialLeft.Length + countToTenInitialRight.Length); for (var i = 0; i < countToTenConcatenated.Length; i++) { Assert.Equal(countToTenConcatenated[i], countToTenConcatenatedExpected[i]); } Assert.Equal(countToTenConcatenatedExpected, countToTenConcatenated); }
public void LinearOffsetCoderUnitTest() { string path = "linearCoderTest"; if (File.Exists(path)) { File.Delete(path); } var linearCoder = new LinearEncoder(path, 64); var expected = new byte[15][]; for (int i = 0; i < expected.Length; i++) { expected[i] = new byte[64]; for (int j = 0; j < 64; j++) { expected[i][j] = (byte)(33 + j + i); //test data } } linearCoder.Append(expected); var actual = linearCoder.ReadData(); for (int i = 0; i < expected.Length; i++) { Assert.IsTrue(ArrayManipulator.Compare(expected[i], actual[i])); } Assert.AreEqual(expected.Length, linearCoder.Count); linearCoder.Remove(1); Assert.AreEqual((byte)35, linearCoder.ReadData()[1][0]); }
public static void RunArrays() { var arrays = new ArrayManipulator(); int test = arrays.Sum(new int[] { 1, 2, 3 }); }
private static void Decode(RLPMessage msg) { var firstByte = msg.Remainder.Array[msg.Remainder.Offset]; if (firstByte == 0x80) { msg.Decoded.Add(null); msg.Remainder = msg.Remainder.Slice(1); return; } // single byte if (firstByte <= 0x7f) { msg.Decoded.Add(new byte[] { firstByte }); msg.Remainder = msg.Remainder.Slice(1); return; } // string <55 bytes if (firstByte <= 0xb7) { var itemLength = Math.Abs(128 - firstByte); var data = firstByte == 0x80 ? new ArraySegment <byte>(new byte[0]) : msg.Remainder.Slice(1, itemLength); msg.Decoded.Add(ArrayManipulator.SubArray(data.Array, data.Offset, data.Count)); msg.Remainder = msg.Remainder.Slice(data.Count + 1); return; } // string >55 bytes if (firstByte <= 0xbf) { var lengthBytesCount = Math.Abs(LargeItemOffset - firstByte); var lengthBytes = new byte[4]; var startIndex = Math.Abs(lengthBytesCount - 5) - 1; for (int i = 0; i < lengthBytesCount; i++) { lengthBytes[startIndex + i] = msg.Remainder.Array[msg.Remainder.Offset + i + 1]; } var itemLength = ByteManipulator.GetUInt32(lengthBytes); var data = msg.Remainder.Slice(lengthBytesCount + 1, (int)itemLength); msg.Decoded.Add(ArrayManipulator.SubArray(msg.Remainder.Array, data.Offset, data.Count)); msg.Remainder = msg.Remainder.Slice(data.Count + lengthBytesCount + 1); return; } // collection <55 bytes if (firstByte <= 0xf7) { var itemLength = Math.Abs(192 - firstByte); var data = msg.Remainder.Slice(1, itemLength).ToArray(); while (msg.Remainder.Offset < msg.Remainder.Array.Length) { var decoded = Decode(data); msg.Decoded.AddRange(decoded); msg.Remainder = msg.Remainder.Slice(msg.Remainder.Count); } return; } // collection >55 bytes if (firstByte <= 0xff) { var lengthBytesCount = Math.Abs(247 - firstByte); var lengthBytes = new byte[4]; var startIndex = Math.Abs(lengthBytesCount - 5) - 1; for (int i = 0; i < lengthBytesCount; i++) { lengthBytes[startIndex + i] = msg.Remainder.Array[msg.Remainder.Offset + i + 1]; } var itemLength = ByteManipulator.GetUInt32(lengthBytes); var data = msg.Remainder.Slice(lengthBytesCount + 1, (int)itemLength).ToArray(); while (msg.Remainder.Offset < msg.Remainder.Array.Length) { var decoded = Decode(data); msg.Decoded.AddRange(decoded); msg.Remainder = msg.Remainder.Slice(msg.Remainder.Count); } return; } }
public static bool operator !=(Transaction a, Transaction b) { return(!ArrayManipulator.Compare(a.Serialize(), b.Serialize())); }
public bool Verify() { return(ArrayManipulator.Compare(MainNetwork, Network) && CryptographyHelper.Secp256k1Verify(Source, Signature, SigningData())); }
public void ProcessBlocks(List <Block> blocks) { var validBlocks = GetContinousValidBlocks(blocks); if (validBlocks.Count != 0) { CleanForks(); var firstBlockChain = GetFork(validBlocks[0].PreviousBlockHash); if (firstBlockChain != null) //skip every block if first valid block does not continue in any chain { var previousBlock = firstBlockChain.GetByHash(validBlocks[0].PreviousBlockHash); if (previousBlock.Height == validBlocks[0].Height - 1) { for (int i = 0; i < validBlocks.Count; i++) { var fork = GetFork(validBlocks[i].GetHash(), firstBlockChain); if (fork == null) //new block(s) :) { validBlocks = ArrayManipulator.SubArray(validBlocks.ToArray(), i, validBlocks.Count - i).ToList(); break; } firstBlockChain = fork; previousBlock = validBlocks[i]; } if (validBlocks.Count != 0) { var newBlocks = new List <Block>(); if (ValidateDifficulty(validBlocks, firstBlockChain)) { for (int i = 0; i < validBlocks.Count; i++) { if (validBlocks[i].Height > previousBlock.Height) { newBlocks.Add(validBlocks[i]); } } var virtualForkBlocks = CreateVirtualFork(firstBlockChain.GetByHash(newBlocks[0].PreviousBlockHash), newBlocks); var forkBlockHeight = virtualForkBlocks[0].Height; var reverseBlocks = main.GetBlocks(forkBlockHeight, (int)(main.Height - forkBlockHeight + 1)); //0 is common block var balanceDiff = ProcessBalanceDiff(Direction.Reverse, reverseBlocks); if (balanceDiff != null) { balanceDiff = ProcessBalanceDiff(Direction.Forward, virtualForkBlocks, balanceDiff); var writeWatch = new Stopwatch(); writeWatch.Start(); if (balanceDiff != null) //nonces and balances are ok { Chain fork; if (newBlocks[0].Height != firstBlockChain.Height + 1) //fork { fork = Fork(virtualForkBlocks); } else //block addition { fork = firstBlockChain; foreach (var block in newBlocks) { firstBlockChain.AddBlock(block); } } if (IsHeavyest(fork)) { balanceLedger.ApplyDiff(balanceDiff); if (fork != main) { SetMain(fork); } } } writeWatch.Stop(); Console.WriteLine("[ChainManager] Write time:" + writeWatch.Elapsed); } } } } } } }
public override bool Equals(object obj) { var transaction = obj as Transaction; return(ArrayManipulator.Compare(Serialize(), transaction.Serialize())); }
public static int[] Action(int[] nums, ArrayManipulator opr) { return(opr(nums)); }