Пример #1
0
        public void Extension_Bytes()
        {
            var hexString = "d52828f9194553d3c96ca255140ed7b223b4edbe686d5be594fcc984f3e2e2d1fc5779027451e033e6264db1708fdc12ad7629d902372c68cd43651d7bcee0e689d158bc94d53ed1d3bad84120a9740420b7d77cb908cec42b113530ecc3b7174666279e";
            var bytes     = HexUtil.HexToBytes(hexString);
            var encoded   = bytes.ToHexString();

            Assert.Equal(hexString, encoded);
        }
Пример #2
0
        /// <summary>
        /// Decodes a hex string to bytes and computes the hash.
        /// </summary>
        /// <param name="hexString">The hex string to be decoded into bytes and hashed.</param>
        /// <returns></returns>
        public static byte[] FromHex(string hexString)
        {
            var input  = HexUtil.HexToBytes(hexString);
            var output = new byte[32];

            ComputeHash(input, output);
            return(output);
        }
Пример #3
0
        public void Decode_Uppercase()
        {
            var hexString = "D52828F9194553D3C96CA255140ED7B223B4EDBE686D5BE594FCC984F3E2E2D1FC5779027451E033E6264DB1708FDC12AD7629D902372C68CD43651D7BCEE0E689D158BC94D53ED1D3BAD84120A9740420B7D77CB908CEC42B113530ECC3B7174666279E";
            var decoded   = HexUtil.HexToBytes(hexString);
            var recoded   = HexUtil.GetHexFromBytes(decoded);

            Assert.Equal(hexString.ToLowerInvariant(), recoded);
        }
Пример #4
0
        public void Decode_0xPrefix()
        {
            var hexString = "0xd52828f9194553d3c96ca255140ed7b223b4edbe686d5be594fcc984f3e2e2d1fc5779027451e033e6264db1708fdc12ad7629d902372c68cd43651d7bcee0e689d158bc94d53ed1d3bad84120a9740420b7d77cb908cec42b113530ecc3b7174666279e";
            var decoded   = HexUtil.HexToBytes(hexString);
            var recoded   = HexUtil.GetHexFromBytes(decoded, hexPrefix: true);

            Assert.Equal(hexString, recoded);
        }
Пример #5
0
        public void UInt8FixedArray()
        {
            var encodedArr = "00000000000000000000000000000000000000000000000000000000000000070000000000000000000000000000000000000000000000000000000000000026000000000000000000000000000000000000000000000000000000000000009600000000000000000000000000000000000000000000000000000000000000e70000000000000000000000000000000000000000000000000000000000000046";
            var buff       = new AbiDecodeBuffer(encodedArr, "uint8[5]");

            DecoderFactory.Decode("uint8[5]", ref buff, out byte[] result, EncoderFactory.LoadEncoder("uint8", default(byte)));
            Assert.Equal(0, buff.HeadCursor.Length);
            byte[] expected = HexUtil.HexToBytes("072696e746");
            Assert.Equal(expected, result);
        }
Пример #6
0
        public void Bytes_M()
        {
            var encodedBytes22 = "072696e74657220746f6f6b20612067616c6c657920600000000000000000000";
            var buff           = new AbiDecodeBuffer(encodedBytes22, "bytes22");

            DecoderFactory.Decode("bytes22", ref buff, out byte[] result);
            Assert.Equal(0, buff.HeadCursor.Length);

            byte[] expected = HexUtil.HexToBytes("072696e74657220746f6f6b20612067616c6c6579206");
            Assert.Equal(expected, result);
        }
Пример #7
0
        public override void SetValue(object val)
        {
            switch (val)
            {
            case IEnumerable <byte> e:
                SetValue(e);
                break;

            case string str:
                SetValue(HexUtil.HexToBytes(str));
                break;

            case byte n:
                SetValue(new byte[] { n });
                break;

            case sbyte n:
                SetValue(HexConverter.GetHexFromInteger(n).HexToBytes());
                break;

            case short n:
                SetValue(HexConverter.GetHexFromInteger(n).HexToBytes());
                break;

            case ushort n:
                SetValue(HexConverter.GetHexFromInteger(n).HexToBytes());
                break;

            case int n:
                SetValue(HexConverter.GetHexFromInteger(n).HexToBytes());
                break;

            case uint n:
                SetValue(HexConverter.GetHexFromInteger(n).HexToBytes());
                break;

            case long n:
                SetValue(HexConverter.GetHexFromInteger(n).HexToBytes());
                break;

            case ulong n:
                SetValue(HexConverter.GetHexFromInteger(n).HexToBytes());
                break;

            case UInt256 n:
                SetValue(HexConverter.GetHexFromInteger(n).HexToBytes());
                break;

            default:
                ThrowInvalidTypeException(val);
                break;
            }
        }
Пример #8
0
        public Address(string hexString)
        {
            if (hexString.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                hexString = hexString.Substring(2);
            }

            // special handling for default/empty address 0x0
            bool allZeros = true;

            for (var i = 0; i < hexString.Length; i++)
            {
                if (hexString[i] != '0')
                {
                    allZeros = false;
                    break;
                }
            }

            if (allZeros)
            {
                _p1 = 0;
                _p2 = 0;
                _p3 = 0;
                _p4 = 0;
                _p5 = 0;
                return;
            }

            if (hexString.Length != 40)
            {
                throw new ArgumentException("Address hex string should be 40 chars long, or 42 with a 0x prefix, was given " + hexString.Length, nameof(hexString));
            }

            Span <byte> bytes = HexUtil.HexToBytes(hexString);

            if (!ValidChecksum(hexString))
            {
                throw new ArgumentException("Address does not pass mixed-case checksum validation, https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md");
            }

            var uintView = MemoryMarshal.Cast <byte, uint>(bytes);

            _p1 = uintView[0];
            _p2 = uintView[1];
            _p3 = uintView[2];
            _p4 = uintView[3];
            _p5 = uintView[4];
        }
Пример #9
0
        public Session(AccountConfig account)
        {
            if (account.Username.Length > 16)
            {
                throw new ArgumentException("Account username must be 16 characters or less.");
            }

            if (account.Password.Length > 20)
            {
                throw new ArgumentException("Account password must be 20 characters or less.");
            }

            _account = account;
            _crypto  = new AesCrypto(HexUtil.HexToBytes(_account.AesKey));
            _client  = new TcpClient();
        }
Пример #10
0
        /// <summary>
        ///     Constructs and sends the <see cref="PacketOut.Login"/> packet to Wolfteam.
        /// </summary>
        /// <returns></returns>
        public async Task LoginAsync()
        {
            using (var packet = new PacketComposer(PacketOut.Login))
            {
                // Add username (16 bytes).
                packet.Writer.Write(Encoding.ASCII.GetBytes(_account.Username));    // Username.
                packet.Writer.Write(new byte[16 - _account.Username.Length]);       // Username padding (to 16 bytes).

                // Add unknown  (16 bytes).
                packet.Writer.Write(_account.AuthRandom);               // Auth uk (4 bytes).
                packet.Writer.Write(HexUtil.HexToBytes("60F41900"));    // Unknown (4 bytes).
                packet.Writer.Write(HexUtil.HexToBytes("41F3DADA"));    // Unknown (4 bytes) (Changes in between requests through real client).
                packet.Writer.Write(HexUtil.HexToBytes("60F41900"));    // Unknown (4 bytes).

                // Add second payload (32 bytes)
                using (var subPacketStream = new MemoryStream(32))
                    using (var subPacket = new BinaryWriter(subPacketStream))
                    {
                        subPacket.Write(Encoding.ASCII.GetBytes(_account.Password)); // Password.
                        subPacket.Write(new byte[20 - _account.Password.Length]);    // Password padding (to 20 bytes).
                        subPacket.Write(WolfteamConfig.ClientVersion);               // Client version (4 bytes).

                        // Add checksums.
                        const int subPacketId     = 4114;
                        var       subPacketBuffer = subPacketStream.ToArray();
                        if (subPacketBuffer.Length % 12 != 0)
                        {
                            throw new Exception("Buffer length must be a multiple of 12.");
                        }

                        // Write checksums.
                        subPacket.Seek(0, SeekOrigin.Begin);

                        for (var index = 0; index < subPacketBuffer.Length / 12; index++)
                        {
                            subPacket.Write(WolfteamConfig.MagicChecksum + subPacketId);
                            subPacket.Write(subPacketBuffer, index * 12, 12);
                        }

                        // Append to main packet.
                        packet.AppendPayload(await _crypto.EncryptAsync(subPacketStream.ToArray()));
                    }

                await SendPacketAsync(packet);
            }
        }
Пример #11
0
        public void Bytes_M()
        {
            byte[] bytes   = HexUtil.HexToBytes("072696e74657220746f6f6b20612067616c6c6579206");
            var    encoder = EncoderFactory.LoadEncoder("bytes22", bytes);

            Assert.IsType <BytesMEncoder>(encoder);
            var encodedSize = encoder.GetEncodedSize();

            Assert.True(encodedSize % 32 == 0);
            Assert.Equal(32, encodedSize);
            Span <byte> data = new byte[encodedSize];
            var         buff = new AbiEncodeBuffer(data, "bytes22");

            encoder.Encode(ref buff);
            Assert.Equal(0, buff.HeadCursor.Length);
            var result = HexUtil.GetHexFromBytes(data);

            Assert.Equal("072696e74657220746f6f6b20612067616c6c657920600000000000000000000", result);
        }
Пример #12
0
        public void Bytes()
        {
            byte[] bytes   = HexUtil.HexToBytes("207072696e74657220746f6f6b20612067616c6c6579206f66207479706520616e6420736372616d626c656420697420746f206d616b65206120747970");
            var    encoder = EncoderFactory.LoadEncoder("bytes", bytes);

            Assert.IsType <BytesEncoder>(encoder);
            var encodedSize = encoder.GetEncodedSize();

            Assert.True(encodedSize % 32 == 0);
            Assert.Equal(128, encodedSize);
            Span <byte> data = new byte[encodedSize];
            var         buff = new AbiEncodeBuffer(data, "bytes");

            encoder.Encode(ref buff);
            Assert.Equal(0, buff.HeadCursor.Length);
            var result = HexUtil.GetHexFromBytes(data);

            Assert.Equal("0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003d207072696e74657220746f6f6b20612067616c6c6579206f66207479706520616e6420736372616d626c656420697420746f206d616b65206120747970000000", result);
        }
Пример #13
0
        public void UInt8FixedArray()
        {
            byte[] bytes   = HexUtil.HexToBytes("072696e746");
            var    encoder = EncoderFactory.LoadEncoder("uint8[5]", bytes, EncoderFactory.LoadEncoder("uint8", default(byte)));

            Assert.IsType <FixedArrayEncoder <byte> >(encoder);
            var encodedSize = encoder.GetEncodedSize();

            Assert.True(encodedSize % 32 == 0);
            Assert.Equal(160, encodedSize);
            Span <byte> data = new byte[encodedSize];
            var         buff = new AbiEncodeBuffer(data, "uint8[5]");

            encoder.Encode(ref buff);
            Assert.Equal(0, buff.HeadCursor.Length);
            var result = HexUtil.GetHexFromBytes(data);

            Assert.Equal("00000000000000000000000000000000000000000000000000000000000000070000000000000000000000000000000000000000000000000000000000000026000000000000000000000000000000000000000000000000000000000000009600000000000000000000000000000000000000000000000000000000000000e70000000000000000000000000000000000000000000000000000000000000046", result);
        }
Пример #14
0
        public void BlockObject()
        {
            var blockJson = File.ReadAllText("TestData/rpc_block_object.json");
            var block     = JsonConvert.DeserializeObject <Block>(blockJson, new JsonSerializerSettings {
                MissingMemberHandling = MissingMemberHandling.Error
            });
            var toJson = JsonConvert.SerializeObject(block, Formatting.Indented);

            var jdp     = new JsonDiffPatch();
            var diff    = JObject.Parse(jdp.Diff(blockJson, toJson));
            var diffStr = diff.ToString(Formatting.Indented);

            foreach (var item in diff)
            {
                var vals = item.Value.Values();
                var b1   = HexUtil.HexToBytes(vals[0].ToString()).ToHexString(hexPrefix: true);
                var b2   = HexUtil.HexToBytes(vals[1].ToString()).ToHexString(hexPrefix: true);
                Assert.Equal(b1, b2);
            }
        }
Пример #15
0
        public Hash(string hexString)
        {
            if (hexString.Length == (SIZE * 2) + 2)
            {
                if (hexString.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                {
                    hexString = hexString.Substring(2);
                }
            }

            if (hexString.Length != SIZE * 2)
            {
                throw new ArgumentException($"Hash hex string should be {SIZE * 2} chars long, or {(SIZE * 2) + 2} with a 0x prefix, was given " + hexString.Length, nameof(hexString));
            }

            Span <byte> bytes    = HexUtil.HexToBytes(hexString);
            var         uintView = MemoryMarshal.Cast <byte, ulong>(bytes);

            _p1 = uintView[0];
            _p2 = uintView[1];
            _p3 = uintView[2];
            _p4 = uintView[3];
        }
Пример #16
0
        public async Task ArrayOfBytes32()
        {
            List <byte[]> arr1 = new List <byte[]>
            {
                HexUtil.HexToBytes("bd40a10d9d184c3e84998e4ee8b29209"),
                HexUtil.HexToBytes("17dcf4ae6b024ce0afc99bd9b4ca7b69"),
                HexUtil.HexToBytes("5325195d6e3a40e2a1836a4da4478c88")
            };

            List <byte[]> arr2 = new List <byte[]>
            {
                HexUtil.HexToBytes("99bd9b4ca7b695325195d6e3a40e2a18"),
                HexUtil.HexToBytes("8b2920917dcf4ae6b024ce0afc99bd9b"),
                HexUtil.HexToBytes("920917dcf4ae6b024ce0afc99bd9b4ca")
            };

            var a_static = await _contract.takeBytes32ArrayStatic(arr1).FirstEventLog <ArrayEncodingTests.Bytes32Event>();

            var a_dyn = await _contract.takeBytes32ArrayDynamic(arr1).FirstEventLog <ArrayEncodingTests.Bytes32Event>();

            var b_static = await _contract.takeBytes32ArrayStatic2(arr1, arr2).FirstEventLog <ArrayEncodingTests.Bytes32Event>();

            var b_dyn = await _contract.takeBytes32ArrayDynamic2(arr1, arr2).FirstEventLog <ArrayEncodingTests.Bytes32Event>();

            var c_static = await _contract.takeBytes32ArrayStatic3(arr1, arr2).FirstEventLog <ArrayEncodingTests.Bytes32EventArrayStatic>();

            var c_dynamic = await _contract.takeBytes32ArrayDynamic3(arr1, arr2).FirstEventLog <ArrayEncodingTests.Bytes32EventArrayDynamic>();

            // BROKE: exception decoding array
            var d_static = await _contract.getBytes32ArrayStatic().Call();

            // BROKE: the last bytes32[] in the return tuple overwrites the previous in decoding
            var d_dyn = await _contract.getBytes32ArrayDynamic().Call();

            Assert.Inconclusive("Solc bug causes bad return values for tuples of arrays");
        }
Пример #17
0
        static async Task PerformContractTransactions(LocalTestNet localTestNet, EntryPointContract entryContract, SolcBytecodeInfo contractBytecode, Abi entryFunction)
        {
            // Perform the contract deployment transaction
            var deployParams = new TransactionParams
            {
                From     = localTestNet.Accounts[0],
                Gas      = ArbitraryDefaults.DEFAULT_GAS_LIMIT,
                GasPrice = ArbitraryDefaults.DEFAULT_GAS_PRICE
            };
            var contractAddress = await ContractFactory.Deploy(localTestNet.RpcClient, HexUtil.HexToBytes(contractBytecode.Bytecode), deployParams);

            var contractInstance = new ContractInstance(
                entryContract.ContractPath, entryContract.ContractName,
                localTestNet.RpcClient, contractAddress, localTestNet.Accounts[0]);


            // If entry function is specified then send transasction to it.
            if (entryFunction != null)
            {
                var callData     = EncoderUtil.GetFunctionCallBytes($"{entryFunction.Name}()");
                var ethFunc      = EthFunc.Create(contractInstance, callData);
                var funcTxParams = new TransactionParams
                {
                    From     = localTestNet.Accounts[0],
                    Gas      = ArbitraryDefaults.DEFAULT_GAS_LIMIT,
                    GasPrice = ArbitraryDefaults.DEFAULT_GAS_PRICE
                };
                await ethFunc.SendTransaction(funcTxParams);
            }
        }
Пример #18
0
        public ResxWriter GenerateResx()
        {
            var resxWriter = new ResxWriter();

            resxWriter.AddEntry("SolidityCompilerVersion", _solidityCompilerVersion);

            // Make paths relative
            var solSourceContent = _solSourceContent.ToDictionary(d => Util.GetRelativeFilePath(_solSourceDir, d.Key), d => d.Value);

            // Scan ast json for absolute paths and make them relative
            foreach (var absPathToken in _solcOutput.JObject["sources"].SelectTokens("$..absolutePath").OfType <JValue>())
            {
                var absPath = Util.GetRelativeFilePath(_solSourceDir, absPathToken.Value <string>());
                absPathToken.Value = absPath;
            }

            var solcSourceInfos = new List <SolcSourceInfo>();

            foreach (JProperty item in _solcOutput.JObject["sources"])
            {
                var fileName      = Util.GetRelativeFilePath(_solSourceDir, item.Name);
                var id            = item.Value.Value <int>("id");
                var astObj        = (JObject)item.Value["ast"];
                var sourceContent = solSourceContent[fileName];
                var sourceInfo    = new SolcSourceInfo
                {
                    AstJson    = astObj,
                    FileName   = fileName,
                    ID         = id,
                    SourceCode = sourceContent
                };
                solcSourceInfos.Add(sourceInfo);
            }

            var solcSourceInfosJson = JsonConvert.SerializeObject(solcSourceInfos, Formatting.Indented);

            resxWriter.AddEntry("SourcesList", solcSourceInfosJson);

            var solcBytecodeInfos = new List <SolcBytecodeInfo>();

            foreach (JProperty solFile in _solcOutput.JObject["contracts"])
            {
                foreach (JProperty solContract in solFile.Value)
                {
                    var fileName     = Util.GetRelativeFilePath(_solSourceDir, solFile.Name);
                    var contractName = solContract.Name;

                    var bytecodeObj         = solContract.Value["evm"]["bytecode"];
                    var deployedBytecodeObj = solContract.Value["evm"]["deployedBytecode"];

                    var sourceMap         = bytecodeObj.Value <string>("sourceMap");
                    var sourceMapDeployed = deployedBytecodeObj.Value <string>("sourceMap");

                    var opcodes         = bytecodeObj.Value <string>("opcodes");
                    var opcodesDeployed = deployedBytecodeObj.Value <string>("opcodes");

                    var bytecode         = bytecodeObj.Value <string>("object");
                    var bytecodeDeployed = deployedBytecodeObj.Value <string>("object");

                    var bytecodeHash         = KeccakHash.ComputeHash(HexUtil.HexToBytes(bytecode)).ToHexString();
                    var bytecodeDeployedHash = KeccakHash.ComputeHash(HexUtil.HexToBytes(bytecodeDeployed)).ToHexString();

                    solcBytecodeInfos.Add(new SolcBytecodeInfo
                    {
                        FilePath             = fileName,
                        ContractName         = contractName,
                        SourceMap            = sourceMap,
                        Opcodes              = opcodes,
                        SourceMapDeployed    = sourceMapDeployed,
                        OpcodesDeployed      = opcodesDeployed,
                        Bytecode             = bytecode,
                        BytecodeDeployed     = bytecodeDeployed,
                        BytecodeHash         = bytecodeHash,
                        BytecodeDeployedHash = bytecodeDeployedHash
                    });
                }
            }

            var solcBytecodeInfosJson = JsonConvert.SerializeObject(solcBytecodeInfos, Formatting.Indented);

            resxWriter.AddEntry("ByteCodeData", solcBytecodeInfosJson);

            var contractAbis     = _solcOutput.ContractsFlattened.ToDictionary(c => c.SolFile + "/" + c.ContractName, c => c.Contract.Abi);
            var contractAbisJson = JsonConvert.SerializeObject(contractAbis, Formatting.Indented);

            resxWriter.AddEntry("ContractAbiJson", contractAbisJson);

            return(resxWriter);
        }
Пример #19
0
        protected override void EndProcessing()
        {
            string filePath;

            if (Path.IsPathRooted(FilePath))
            {
                filePath = Path.GetFullPath(FilePath);
            }
            else
            {
                filePath = Path.GetFullPath(Path.Join(SessionState.Path.CurrentLocation.Path, FilePath));
            }

            if (!File.Exists(filePath))
            {
                Host.UI.WriteErrorLine($"File does not exist at: {filePath}");
                return;
            }

            var fileContent = File.ReadAllText(filePath);
            var dataJson    = JObject.Parse(fileContent);

            string[][] accountArrayHex;

            if (dataJson.TryGetValue(LocalAccountsUtil.JSON_ENCRYPTED_ACCOUNTS_KEY, out var token))
            {
                if (string.IsNullOrWhiteSpace(Password))
                {
                    Host.UI.WriteErrorLine($"No password parameter specified and accounts are encryped in file {FilePath}");
                    return;
                }

                var    encrypedAccounts = token.Value <string>();
                string decrypedContent;
                try
                {
                    decrypedContent = AesUtil.DecryptString(encrypedAccounts, Password);
                }
                catch (Exception ex)
                {
                    Host.UI.WriteErrorLine(ex.ToString());
                    Host.UI.WriteErrorLine("Failed to decrypt account data. Incorrect password?");
                    return;
                }

                accountArrayHex = JsonConvert.DeserializeObject <string[][]>(decrypedContent);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(Password))
                {
                    Host.UI.WriteErrorLine($"Password parameter specified but accounts are encryped in file {FilePath}");
                    return;
                }

                accountArrayHex = dataJson[LocalAccountsUtil.JSON_ACCOUNTS_KEY].ToObject <string[][]>();
            }

            var accounts = accountArrayHex
                           .Select(a => EthereumEcdsa.Create(HexUtil.HexToBytes(a[1]), EthereumEcdsaKeyType.Private))
                           .Select(a => (a.EcdsaKeyPairToAddress(), a))
                           .ToArray();

            GlobalVariables.AccountKeys = accounts;

            Host.UI.WriteLine($"Loaded {accounts.Length} accounts from {filePath}");
        }