public void Can_merkleize_uint256_vector_longer() { Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, new UInt256[] { 1, 2, 3, 4 }); Assert.AreEqual("0xbfe3c665d2e561f13b30606c580cb703b2041287e212ade110f0bfd8563e21bb", root.ToHexString(true)); }
public OracleContractManager() { if (!EnsureKeyAcquired()) { Message = "Could not import wallet key for oracle contract."; IsSetup = false; return; } // var keypair = EnsureKeyPair(); // PrivateKey = keypair.PrivateKey; var contractCode = GetContractCode(/*keypair.PublicKey*/); ContractAddress = new Address(Merkle.innerHash(Encoding.ASCII.GetBytes(contractCode)), AddressType.Contract); if (!EnsureContractActive(contractCode)) { Message = "Could not activate oracle contract."; IsSetup = false; return; } if (!EnsureInitialOutpoint()) { Message = "Could not create initial outpoint."; IsSetup = false; return; } Message = ""; IsSetup = true; }
public void Can_merkleize_uint128_vector() { Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, new UInt128[] { 1, 3, 5 }); Assert.AreEqual("0xf189891181de961f99a35c1aa21c0d909bf30bb8bebb760050f3d06dc56e488a", root.ToHexString(true)); }
public void Can_merkleize_bitlist() { Span <byte> root = stackalloc byte[32]; Merkle.IzeBits(root, new byte[] { 123 }, 0); Assert.AreEqual("0xe5e12694be373406e317c583b5fd9e7a642913dc20a5c4947edb202dafbbc0ee", root.ToHexString(true)); }
public void Can_merkleize_bool_vector() { Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, new [] { true, false }); Assert.AreEqual("0x0100000000000000000000000000000000000000000000000000000000000000", root.ToHexString(true)); }
public void Can_merkleize_ulong_vector() { Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, new [] { 1UL, 3UL }); Assert.AreEqual("0x0100000000000000030000000000000000000000000000000000000000000000", root.ToHexString(true)); }
public void Can_merkleize_bitlist_high_limit_and_null() { Span <byte> root = stackalloc byte[32]; Merkle.IzeBits(root, new byte[] { 0 }, 8); Assert.AreEqual("0x881690bb860e3a4f7681f51f1eccc59dac2718eeb0c0585cd698ad0650938b33", root.ToHexString(true)); }
public void Can_merkleize_bitlist_with_limit() { Span <byte> root = stackalloc byte[32]; Merkle.IzeBits(root, new byte[] { 17 }, 2); Assert.AreEqual("0x60d461bd1cec1a858ba48a27799c9686c15ad1625743bafa70674afc530f981a", root.ToHexString(true)); }
public void Can_merkleize_bitvector() { Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, new byte[] { 123 }); Assert.AreEqual("0x7b00000000000000000000000000000000000000000000000000000000000000", root.ToHexString(true)); }
public void Can_merkleize_bitlist_high_limit_and_small() { Span <byte> root = stackalloc byte[32]; Merkle.IzeBits(root, new byte[] { 3 }, 8); Assert.AreEqual("0x9e1ff035a32c3d3085074e676356984c077f70bed47814956a9ef8852dcb8161", root.ToHexString(true)); }
public void Can_merkleize_byte() { Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, (byte)34); Assert.AreEqual("0x2200000000000000000000000000000000000000000000000000000000000000", root.ToHexString(true)); }
public void Can_merkleize_int() { Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, 34 + byte.MaxValue + ushort.MaxValue); Assert.AreEqual("0x2001010000000000000000000000000000000000000000000000000000000000", root.ToHexString(true)); }
public void Can_merkleize_uint128_vector_full() { Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, new UInt128[] { 1, 3 }); Assert.AreEqual("0x0100000000000000000000000000000003000000000000000000000000000000", root.ToHexString(true)); }
public void CanSerDesTx2() { var tx = Consensus.Tests.tx; var data = Merkle.serialize <Types.Transaction>(tx); var t = Serialization.context.GetSerializer <Types.Transaction>().UnpackSingleObject(data); Assert.IsTrue(t.Equals(tx)); }
public void TestCase() { Types.Block block = Util.GetBlock(null, 0); var data = Merkle.serialize <Types.Block>(block); Types.Block _block = Serialization.context.GetSerializer <Types.Block>().UnpackSingleObject(data); Assert.IsTrue(block.Equals(_block)); }
public Block(Config config, BlockHeader header, List <Transaction> data) { if (data == null) { data = new List <Transaction>(); } Header = header; Data = data; MerkleRoot = (data.Count != 0) ? Merkle.GetMerkleRoot(config, Data) : "Not available due to transaction count."; }
public void Can_merkleize_uint256() { UInt256 input = UInt256.Zero; input += 34; input += byte.MaxValue; input += ushort.MaxValue; input += uint.MaxValue; input += ulong.MaxValue; Span <byte> root = stackalloc byte[32]; Merkle.Ize(root, input); Assert.AreEqual("0x1e01010001000000010000000000000000000000000000000000000000000000", root.ToHexString(true)); }
public void UpdateContractInfo() { var contractCode = _ContractView.Code; _Code = Encoding.ASCII.GetBytes(contractCode); _Hash = Merkle.innerHash(Encoding.ASCII.GetBytes(contractCode)); _ContractView.Hash = _Hash; _ContractView.CostPerBlock = ActiveContractSet.KalapasPerBlock(contractCode); //new GetIsContractActiveAction(_Hash).Publish().Result // var isActive = new GetIsContractActiveAction(_Hash).Publish(); //_ContractView.IsActive = ; }
public void CanSerDesTx() { var p = new TestTransactionPool(); p.Add("test", 1); p.Render(); var test = p.TakeOut("test").Value; var data = Merkle.serialize <Types.Transaction>(test); var t = Serialization.context.GetSerializer <Types.Transaction>().UnpackSingleObject(data); Assert.IsTrue(t.Equals(test)); }
public ActionResult Post() { Directory.CreateDirectory(Path.Combine("db", "contracts")); Directory.CreateDirectory(Path.Combine("db", "asset-metadata")); var contractCode = Utils.Dos2Unix(Request["contractCode"]); var contractHash = Merkle.innerHash(Encoding.ASCII.GetBytes(contractCode)); var file = $"{HttpServerUtility.UrlTokenEncode(contractHash)}"; if (!System.IO.File.Exists(file)) { System.IO.File.WriteAllText(Path.ChangeExtension(Path.Combine("db", "contracts", file), ".txt"), contractCode); } System.IO.File.WriteAllText(Path.ChangeExtension(Path.Combine("db", "asset-metadata", file), ".json"), JsonConvert.SerializeObject(new AssetMetadata() { name = Request["assetName"], imageUrl = Request["assetImageURL"], version = Request["assetMatadataVersion"] })); return(View("Index")); }
void HandleTx(TransactionValidation.PointedTransaction ptx) { //TODO: try simplify using hash from message var txHash = Merkle.transactionHasher.Invoke(TransactionValidation.unpoint(ptx)); var activationSacrifice = 0UL; for (var i = 0; i < ptx.outputs.Length; i++) { var output = ptx.outputs[i]; if ([email protected]) { if (!output.spend.asset.SequenceEqual(Tests.zhash)) { continue; // not Zen } var contractSacrificeLock = (Types.OutputLock.ContractSacrificeLock)output.@lock; if (contractSacrificeLock.IsHighVLock) { continue; // not current version } if (contractSacrificeLock.Item.lockData.Length == 0) { activationSacrifice += output.spend.amount; } } //todo: fix to exclude CSLocks&FLocks, instead of including by locktype if ([email protected] || [email protected]) { var outpoint = new Types.Outpoint(txHash, (uint)i); _UtxoSet.Add(new Tuple <Types.Outpoint, Types.Output>(outpoint, output)); } } if (FSharpOption <Types.ExtendedContract> .get_IsSome(ptx.contract) && !ptx.contract.Value.IsHighVContract) { var codeBytes = ((Types.ExtendedContract.Contract)ptx.contract.Value).Item.code; var contractHash = Merkle.innerHash(codeBytes); var contractCode = System.Text.Encoding.ASCII.GetString(codeBytes); if (!_ActiveContracts.Contains(contractHash)) { if (activationSacrifice > ActiveContractSet.KalapasPerBlock(contractCode)) { try { var compiledCodeOpt = ContractExamples.FStarExecution.compile(contractCode); if (FSharpOption <byte[]> .get_IsSome(compiledCodeOpt)) { _ActiveContracts.Add(contractHash); } } catch (Exception e) { MinerTrace.Error("Could not compile contract " + Convert.ToBase64String(contractHash), e); } } } } }
public void Can_get_the_next_power_of_two_64(ulong value, ulong expectedResult) { Assert.AreEqual(expectedResult, Merkle.NextPowerOfTwo(value)); }
void RecalculateHeader() { if (_BlockChain.Tip == null) { return; } if (_TransactionQueue.IsStuck) { MinerTrace.Information("Queue is stuck. count = " + _TransactionQueue.Count); } while (!_TransactionQueue.IsStuck && _ValidatedTxs.Count < TxsPerBlockLimit) { var ptx = _TransactionQueue.Take(); if (IsTransactionValid(ptx)) { _ValidatedTxs.Add(ptx); _TransactionQueue.Remove(); HandleTx(ptx); } else { MinerTrace.Information("Tx invalid"); _TransactionQueue.Next(); } } if (_ValidatedTxs.Count == 0) { MinerTrace.Information("No txs"); return; // don't allow empty blocks } CalculateCoinbase(); var txs = ListModule.OfSeq(FSharpList <Types.Transaction> .Cons(_Coinbase, ListModule.OfSeq(_ValidatedTxs.Select(TransactionValidation.unpoint)))); _Header = new Types.BlockHeader( 0, _BlockChain.Tip.Key, _BlockChain.Tip.Value.header.blockNumber + 1, Merkle.merkleRoot( new byte[] { }, Merkle.transactionHasher, txs ), new byte[] { }, new byte[] { }, ListModule.Empty <byte[]>(), DateTime.Now.ToUniversalTime().Ticks, Difficulty, new byte[12] ); MinerTrace.Information($"Mining block number {_BlockChain.Tip.Value.header.blockNumber + 1} with {_ValidatedTxs.Count()} txs"); _Hasher.SetHeader(_Header); _Hasher.Continue(); }
public bool GetContractActivationTx(byte[] code, ulong zenAmount, out Types.Transaction signedTx, byte[] secureTokenHash = null) { ulong change; var assets = new List <Asset>(); var outputs = new List <Types.Output>(); using (TransactionContext dbTx = _DBContext.GetTransactionContext()) { if (!GetAssets(dbTx, Tests.zhash, zenAmount, out change, assets)) { signedTx = null; return(false); } else if (change > 0) { Key key; if (_KeyStore.GetUnusedKey(dbTx, out key, true)) { _Keys.Add(key); dbTx.Commit(); } outputs.Add(new Types.Output(key.Address.GetLock(), new Types.Spend(Tests.zhash, change))); } if (secureTokenHash != null) { ulong secureTokenChange; // var secureTokenAssets = new Assets(); if (!GetAssets(dbTx, secureTokenHash, 1, out secureTokenChange, assets)) { signedTx = null; return(false); } else if (secureTokenChange > 0) { Key key; if (_KeyStore.GetUnusedKey(dbTx, out key, true)) { _Keys.Add(key); dbTx.Commit(); } outputs.Add(new Types.Output(key.Address.GetLock(), new Types.Spend(secureTokenHash, secureTokenChange))); } } } var output = new Types.Output( Types.OutputLock.NewContractSacrificeLock( new Types.LockCore(0, ListModule.OfSeq(new byte[][] { })) ), new Types.Spend(Tests.zhash, zenAmount) ); outputs.Add(output); if (secureTokenHash != null) { outputs.Add(new Types.Output(Types.OutputLock.NewContractLock(Merkle.innerHash(code), new byte[] { }), new Types.Spend(secureTokenHash, 1))); } signedTx = TransactionValidation.signTx(new Types.Transaction( 0, ListModule.OfSeq(assets.Select(t => t.Outpoint)), ListModule.OfSeq(new List <byte[]>()), ListModule.OfSeq(outputs), new Microsoft.FSharp.Core.FSharpOption <Types.ExtendedContract>( Types.ExtendedContract.NewContract(new Types.Contract(code, new byte[] { }, new byte[] { })) ) ), ListModule.OfSeq(assets.Select(i => i.Key.Private))); return(true); }
private static bool RunGenericSszTests(string category) { bool success = true; string[] valid = Directory.GetDirectories(Path.Combine("generic", category, "valid")); string[] invalid = Directory.GetDirectories(Path.Combine("generic", category, "invalid")); foreach (string validDir in valid) { TestContext.Out.WriteLine(validDir); string[] files = Directory.GetFiles(validDir); (YamlNode valueNode, YamlNodeType valueType) = LoadValue(Path.Combine(validDir, "value.yaml")); (YamlNode merkleRootYaml, _) = LoadValue(Path.Combine(validDir, "meta.yaml")); UInt256.CreateFromLittleEndian(out UInt256 expectedMerkleRoot, Bytes.FromHexString(((YamlScalarNode)merkleRootYaml["root"]).Value)); Span <byte> output = null; Span <byte> ssz = File.ReadAllBytes(Path.Combine(validDir, "serialized.ssz")); if (valueType == YamlNodeType.Sequence) { YamlSequenceNode sequenceNode = (YamlSequenceNode)valueNode; if (validDir.Contains("bool")) { bool[] value = sequenceNode.Children.Cast <YamlScalarNode>().Select(sn => bool.Parse(sn?.Value ?? "false")).ToArray(); bool[] valueFromSsz = Nethermind.Ssz.Ssz.DecodeBools(ssz).ToArray(); output = new byte[value.Length]; Nethermind.Ssz.Ssz.Encode(output, value); byte[] clone = output.ToArray(); Nethermind.Ssz.Ssz.Encode(output, valueFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint256")) { UInt256[] value = sequenceNode.Children.Cast <YamlScalarNode>().Select(sn => UInt256.Parse(sn.Value)).ToArray(); UInt256[] valueFromSsz = Nethermind.Ssz.Ssz.DecodeUInts256(ssz); output = new byte[value.Length * 32]; Nethermind.Ssz.Ssz.Encode(output, value); byte[] clone = output.ToArray(); Nethermind.Ssz.Ssz.Encode(output, valueFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint128")) { UInt128[] value = sequenceNode.Children.Cast <YamlScalarNode>().Select(sn => UInt128.Parse(sn.Value)).ToArray(); UInt128[] valueFromSsz = Nethermind.Ssz.Ssz.DecodeUInts128(ssz); output = new byte[value.Length * 16]; Nethermind.Ssz.Ssz.Encode(output, value); byte[] clone = output.ToArray(); Nethermind.Ssz.Ssz.Encode(output, valueFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint64")) { ulong[] value = sequenceNode.Children.Cast <YamlScalarNode>().Select(sn => ulong.Parse(sn.Value ?? ulong.MinValue.ToString())).ToArray(); ulong[] valueFromSsz = Nethermind.Ssz.Ssz.DecodeULongs(ssz).ToArray(); output = new byte[value.Length * 8]; Nethermind.Ssz.Ssz.Encode(output, value); byte[] clone = output.ToArray(); Nethermind.Ssz.Ssz.Encode(output, valueFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint32")) { uint[] value = sequenceNode.Children.Cast <YamlScalarNode>().Select(sn => uint.Parse(sn.Value ?? uint.MinValue.ToString())).ToArray(); uint[] valueFromSsz = Nethermind.Ssz.Ssz.DecodeUInts(ssz).ToArray(); output = new byte[value.Length * 4]; Nethermind.Ssz.Ssz.Encode(output, value); byte[] clone = output.ToArray(); Nethermind.Ssz.Ssz.Encode(output, valueFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint16")) { ushort[] value = sequenceNode.Children.Cast <YamlScalarNode>().Select(sn => ushort.Parse(sn.Value ?? ushort.MinValue.ToString())).ToArray(); ushort[] valueFromSsz = Nethermind.Ssz.Ssz.DecodeUShorts(ssz).ToArray(); output = new byte[value.Length * 2]; Nethermind.Ssz.Ssz.Encode(output, value); byte[] clone = output.ToArray(); Nethermind.Ssz.Ssz.Encode(output, valueFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint8")) { byte[] value = sequenceNode.Children.Cast <YamlScalarNode>().Select(sn => byte.Parse(sn.Value ?? byte.MinValue.ToString())).ToArray(); byte[] valueFromSsz = Nethermind.Ssz.Ssz.DecodeBytes(ssz).ToArray(); output = new byte[value.Length]; Nethermind.Ssz.Ssz.Encode(output, value); byte[] clone = output.ToArray(); Nethermind.Ssz.Ssz.Encode(output, valueFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } } else if (valueType == YamlNodeType.Scalar) { if (validDir.Contains("bitvec") || validDir.Contains("bitlist")) { uint limit = 0; Match match = Regex.Match(validDir, "bitlist_(\\d+)", RegexOptions.IgnoreCase); if (match.Success) { limit = (uint.Parse(match.Groups[1].Value) + 255) / 256; } byte[] value = Bytes.FromHexString(((YamlScalarNode)valueNode).Value); byte[] valueFromSsz = Nethermind.Ssz.Ssz.DecodeBytes(ssz).ToArray(); output = new byte[value.Length]; Nethermind.Ssz.Ssz.Encode(output, value); byte[] clone = output.ToArray(); Nethermind.Ssz.Ssz.Encode(output, valueFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); UInt256 root; if (validDir.Contains("bitvec")) { Merkle.Ize(out root, valueFromSsz); } else { Merkle.IzeBits(out root, valueFromSsz, limit); } Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("boolean")) { string yamlValue = ((YamlScalarNode)valueNode)?.Value; bool? value = yamlValue is null ? null : (bool?)bool.Parse(yamlValue); bool? valueFromSsz = Nethermind.Ssz.Ssz.DecodeBool(ssz); Assert.AreEqual(value, valueFromSsz); output = new byte[1]; output[0] = Nethermind.Ssz.Ssz.Encode(value ?? false); Merkle.Ize(out UInt256 root, valueFromSsz ?? false); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint_256")) { UInt256 value = UInt256.Parse(((YamlScalarNode)valueNode).Value); UInt256 valueFromSsz = Nethermind.Ssz.Ssz.DecodeUInt256(ssz); Assert.AreEqual(value, valueFromSsz); output = new byte[32]; Nethermind.Ssz.Ssz.Encode(output, value); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint_128")) { UInt128 value = UInt128.Parse(((YamlScalarNode)valueNode).Value); UInt128 valueFromSsz = Nethermind.Ssz.Ssz.DecodeUInt128(ssz); Assert.AreEqual(value, valueFromSsz); output = new byte[16]; Nethermind.Ssz.Ssz.Encode(output, value); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint_64")) { ulong value = ulong.Parse(((YamlScalarNode)valueNode).Value); ulong valueFromSsz = Nethermind.Ssz.Ssz.DecodeULong(ssz); Assert.AreEqual(value, valueFromSsz); output = new byte[8]; Nethermind.Ssz.Ssz.Encode(output, value); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint_32")) { uint value = uint.Parse(((YamlScalarNode)valueNode).Value); uint valueFromSsz = Nethermind.Ssz.Ssz.DecodeUInt(ssz); Assert.AreEqual(value, valueFromSsz); output = new byte[4]; Nethermind.Ssz.Ssz.Encode(output, value); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint_16")) { ushort value = ushort.Parse(((YamlScalarNode)valueNode).Value); ushort valueFromSsz = Nethermind.Ssz.Ssz.DecodeUShort(ssz); Assert.AreEqual(value, valueFromSsz); output = new byte[2]; Nethermind.Ssz.Ssz.Encode(output, value); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } else if (validDir.Contains("uint_8")) { byte value = byte.Parse(((YamlScalarNode)valueNode).Value); byte valueFromSsz = Nethermind.Ssz.Ssz.DecodeByte(ssz); Assert.AreEqual(value, valueFromSsz); output = new byte[1]; Nethermind.Ssz.Ssz.Encode(output, value); Merkle.Ize(out UInt256 root, valueFromSsz); Assert.AreEqual(expectedMerkleRoot, root); } } else if (valueType == YamlNodeType.Mapping) { var mappingNode = (YamlMappingNode)valueNode; if (validDir.Contains("BitsStruct")) { BitsStruct testStruct = ParseBitsStruct(mappingNode); BitsStruct testStructFromSsz = DecodeBitsStruct(ssz); output = new byte[13]; Encode(output, testStruct); byte[] clone = output.ToArray(); Encode(output, testStructFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); } else if (validDir.Contains("SmallTestStruct")) { SmallTestStruct testStruct = ParseSmallTestStruct(mappingNode); SmallTestStruct testStructFromSsz = DecodeSmallTestStruct(ssz); output = new byte[4]; Encode(output, testStruct); byte[] clone = output.ToArray(); Encode(output, testStructFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); } else if (validDir.Contains("SingleFieldTestStruct")) { SingleFieldTestStruct testStruct = new SingleFieldTestStruct(); SingleFieldTestStruct testStructFromSsz = DecodeSingleFieldTestStruct(ssz); testStruct.A = byte.Parse(((YamlScalarNode)mappingNode.Children["A"]).Value); output = new byte[1]; Encode(output, testStruct); byte[] clone = output.ToArray(); Encode(output, testStructFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); } else if (validDir.Contains("VarTestStruct")) { VarTestStruct testStruct = ParseVarTestStruct(mappingNode); VarTestStruct testStructFromSsz = DecodeVarTestStruct(ssz); output = new byte[7 + testStruct.B.Length * 2]; Encode(output, testStruct); byte[] clone = output.ToArray(); Encode(output, testStructFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); } else if (validDir.Contains("FixedTestStruct")) { FixedTestStruct testStruct = ParseFixedTestStruct(mappingNode); FixedTestStruct testStructFromSsz = DecodeFixTestStruct(ssz); output = new byte[13]; Encode(output, testStruct); byte[] clone = output.ToArray(); Encode(output, testStructFromSsz); Assert.AreEqual(clone.ToHexString(), output.ToHexString(), "ssz"); } else if (validDir.Contains("ComplexTestStruct")) { ComplexTestStruct testStruct = ParseComplexTestStruct(mappingNode); output = new byte[8236]; Encode(ref output, testStruct); } } if (ssz.ToHexString() != output.ToHexString()) { TestContext.Out.WriteLine($" expected {ssz.ToHexString()}"); TestContext.Out.WriteLine($" actual {output.ToHexString()}"); success = false; } } return(success); }
bool ExtendMain(List <QueueAction> queuedActions, double totalWork, bool isGenesis = false) { if (_BlockChain.BlockStore.ContainsKey(_DbTx, _BkHash)) { _BlockChain.BlockStore.SetLocation(_DbTx, _BkHash, LocationEnum.Main); } else { _BlockChain.BlockStore.Put(_DbTx, _BkHash, _Bk, LocationEnum.Main, totalWork); } _BlockChain.Timestamps.Push(_Bk.header.timestamp); if (_Bk.header.blockNumber % 2000 == 0) { _BlockChain.BlockNumberDifficulties.Add(_DbTx.Transaction, _Bk.header.blockNumber, _BkHash); } var blockUndoData = new BlockUndoData(); var confirmedTxs = new HashDictionary <TransactionValidation.PointedTransaction>(); //TODO: lock with mempool for (var txIdx = 0; txIdx < _Bk.transactions.Count(); txIdx++) { var tx = _Bk.transactions[txIdx]; var txHash = Merkle.transactionHasher.Invoke(tx); TransactionValidation.PointedTransaction ptx; if (!isGenesis) { if ((txIdx == 0 && !IsCoinbaseTxValid(tx)) || (txIdx > 0 && IsCoinbaseTxValid(tx))) { if (txIdx == 0) { BlockChainTrace.Information("Invalid coinbase tx"); } else { BlockChainTrace.Information($"Invalid tx ({txIdx})"); } return(false); } if (!IsTransactionValid(tx, txHash, out ptx)) { return(false); } confirmedTxs[txHash] = ptx; foreach (var pInput in ptx.pInputs) { _BlockChain.UTXOStore.Remove(_DbTx, pInput.Item1); BlockChainTrace.Information($"utxo spent, amount {pInput.Item2.spend.amount}", ptx); //BlockChainTrace.Information($" of", pInput.Item1.txHash); blockUndoData.RemovedUTXO.Add(new Tuple <Types.Outpoint, Types.Output>(pInput.Item1, pInput.Item2)); } } else { ptx = TransactionValidation.toPointedTransaction( tx, ListModule.Empty <Types.Output>() ); } _BlockChain.BlockStore.TxStore.Put(_DbTx, txHash, tx, true); var contractExtendSacrifices = new HashDictionary <ulong>(); var activationSacrifice = 0UL; for (var outputIdx = 0; outputIdx < tx.outputs.Count(); outputIdx++) { var output = tx.outputs[outputIdx]; if ([email protected]) { if (!output.spend.asset.SequenceEqual(Tests.zhash)) { continue; // not Zen } var contractSacrificeLock = (Types.OutputLock.ContractSacrificeLock)output.@lock; if (contractSacrificeLock.IsHighVLock) { continue; // not current version } if (contractSacrificeLock.Item.lockData.Length > 0 && contractSacrificeLock.Item.lockData[0] != null && contractSacrificeLock.Item.lockData[0].Length > 0) { var contractKey = contractSacrificeLock.Item.lockData[0]; // output-lock-level indicated contract contractExtendSacrifices[contractKey] = (contractExtendSacrifices.ContainsKey(contractKey) ? contractExtendSacrifices[contractKey] : 0) + output.spend.amount; } else if (contractSacrificeLock.Item.lockData.Length == 0) { activationSacrifice += output.spend.amount; } } //todo: fix to exclude CSLocks&FLocks, instead of including by locktype if ([email protected] || [email protected]) { BlockChainTrace.Information($"new utxo, amount {output.spend.amount}", tx); var outpoint = new Types.Outpoint(txHash, (uint)outputIdx); _BlockChain.UTXOStore.Put(_DbTx, outpoint, output); blockUndoData.AddedUTXO.Add(new Tuple <Types.Outpoint, Types.Output>(outpoint, output)); } } if (FSharpOption <Types.ExtendedContract> .get_IsSome(tx.contract) && !tx.contract.Value.IsHighVContract) { var codeBytes = ((Types.ExtendedContract.Contract)tx.contract.Value).Item.code; var contractHash = Merkle.innerHash(codeBytes); var contractCode = System.Text.Encoding.ASCII.GetString(codeBytes); if (_BlockChain.ActiveContractSet.TryActivate(_DbTx, contractCode, activationSacrifice, contractHash, _Bk.header.blockNumber)) { blockUndoData.ACSDeltas.Add(contractHash, new ACSUndoData()); ContractsTxsStore.Add(_DbTx.Transaction, contractHash, txHash); } } foreach (var item in contractExtendSacrifices) { var currentACSItem = _BlockChain.ActiveContractSet.Get(_DbTx, item.Key); if (currentACSItem.Value != null) { if (_BlockChain.ActiveContractSet.TryExtend(_DbTx, item.Key, item.Value)) { if (!blockUndoData.ACSDeltas.ContainsKey(item.Key)) { blockUndoData.ACSDeltas.Add(item.Key, new ACSUndoData() { LastBlock = currentACSItem.Value.LastBlock }); } } } } } var expiringContracts = _BlockChain.ActiveContractSet.GetExpiringList(_DbTx, _Bk.header.blockNumber); foreach (var acsItem in expiringContracts) { if (!blockUndoData.ACSDeltas.ContainsKey(acsItem.Key)) { blockUndoData.ACSDeltas.Add(acsItem.Key, new ACSUndoData() { ACSItem = acsItem.Value }); } } if (!isGenesis) { _BlockChain.BlockStore.SetUndoData(_DbTx, _BkHash, blockUndoData); } _BlockChain.ActiveContractSet.DeactivateContracts(_DbTx, expiringContracts.Select(t => t.Key)); ValidateACS(); _BlockChain.ChainTip.Context(_DbTx).Value = _BkHash; //TODO: only update after commit _BlockChain.Tip = new Keyed <Types.Block>(_BkHash, _Bk); queuedActions.Add(new MessageAction(new BlockMessage(confirmedTxs, _Bk.header.blockNumber))); foreach (var item in confirmedTxs) { ConfirmedTxs[item.Key] = item.Value; UnconfirmedTxs.Remove(item.Key); } return(true); }
public ActionResult Generate() { if (!Directory.Exists("db")) { Directory.CreateDirectory("db"); } var contractManager = new OracleContractManager(); if (!contractManager.IsSetup) { ViewData["Result"] = false; ViewData["Message"] = contractManager.Message; return(View()); } _StockAPI.Tickers = WebConfigurationManager.AppSettings["tickers"].Split(','); var rawTickers = _StockAPI.FetchResults().Result; var now = DateTime.Now.ToUniversalTime(); var nowTicks = now.Ticks; var items = rawTickers.Select(t => new ContractExamples.Oracle.TickerItem(t.Name, t.Value, nowTicks)); var secret = Convert.FromBase64String(WebConfigurationManager.AppSettings["oracleSecret"]); var commitmentData = ContractExamples.Oracle.commitments(items, secret); var getOutpointsResult = Client.Send <GetContractPointedOutputsResultPayload>(NodeRPCAddress, new GetContractPointedOutputsPayload() { ContractHash = contractManager.ContractAddress.Bytes }).Result; if (!getOutpointsResult.Success || getOutpointsResult.PointedOutputs.Count == 0) { ViewData["Result"] = false; ViewData["Message"] = "Could not find outputs"; return(View()); } var utxos = GetContractPointedOutputsResultPayload.Unpack(getOutpointsResult.PointedOutputs); if (utxos.Count() == 0) { ViewData["Result"] = false; ViewData["Message"] = "Could not find output"; return(View()); } var utxo = utxos.First(); //var serializer = new ContractExamples.FStarCompatibility.DataSerializer(Consensus.Serialization.context); //Consensus.Serialization.context.Serializers.RegisterOverride(serializer); var data = ContractUtilities.DataGenerator.makeOracleMessage(commitmentData.Item2, utxo.Item1); //var data = ContractExamples.QuotedContracts.simplePackOutpoint(utxo.Item1) // .Concat(commitmentData.Item2).ToArray(); //var signiture = Authentication.sign(data, contractManager.PrivateKey); //data = data.Concat(signiture).ToArray(); var sendContractResult = Client.Send <SendContractResultPayload>(NodeRPCAddress, new SendContractPayload() { ContractHash = contractManager.ContractAddress.Bytes, Data = data }).Result; ViewData["Result"] = sendContractResult.Success; if (sendContractResult.Success) { var file = Path.Combine("db", $"{now.ToFileTime()}"); MemoryStream ms = new MemoryStream(); ContractExamples.Oracle.proofMapSerializer.WriteObject(ms, commitmentData.Item1); ms.Position = 0; var sr = new StreamReader(ms); System.IO.File.WriteAllText(Path.ChangeExtension(file, ".data.json"), sr.ReadToEnd()); var outpoint = new Types.Outpoint(sendContractResult.TxHash, 1); // oracle always puts data on output #1 System.IO.File.WriteAllText(Path.ChangeExtension(file, ".outpoint.txt"), Convert.ToBase64String(Merkle.serialize(outpoint))); } else { ViewData["Message"] = "Reason: send result was '" + sendContractResult.Message + "'"; } return(View()); }
private static byte[] GetHash(string value) { return(Merkle.innerHash(Encoding.ASCII.GetBytes(value))); }