public string ToPtsAddy()
        {
            var buffer    = ToBuffer(true);
            var firstHash = SHA256.Create().HashAndDispose(buffer);

            buffer.Clear();
            var secondHash = RIPEMD160.Create().HashAndDispose(firstHash);

            firstHash.Clear();
            var hash = new byte[] { 0x38 }.Concat(secondHash); // version 56(decimal)

            secondHash.Clear();
            var firstChecksum  = SHA256.Create().HashAndDispose(hash);
            var secondChecksum = SHA256.Create().HashAndDispose(firstChecksum);

            firstChecksum.Clear();
            var checksum = secondChecksum.Slice(0, 4);

            secondChecksum.Clear();
            buffer = hash.Concat(checksum);
            checksum.Clear();
            hash.Clear();
            var result = Base58CheckEncoding.EncodePlain(buffer);

            buffer.Clear();
            return(result);
        }
Beispiel #2
0
        public static void Do()
        {
            for (var i = 0; i < 100; i++)
            {
                BigInteger randomBigInt    = i;
                var        randomBytes     = new byte[] { 0x00, 0x00, 0x00, 0x00 };
                var        bigIntByteArray = randomBigInt.ToByteArray();
                if (bigIntByteArray.Length == 1)
                {
                    randomBytes[3] = bigIntByteArray[0];
                }

                if (bigIntByteArray.Length == 2)
                {
                    randomBytes[3] = bigIntByteArray[0];
                    randomBytes[2] = bigIntByteArray[1];
                }

                if (bigIntByteArray.Length == 3)
                {
                    randomBytes[3] = bigIntByteArray[0];
                    randomBytes[2] = bigIntByteArray[1];
                    randomBytes[1] = bigIntByteArray[2];
                }

                var base58String = Base58CheckEncoding.EncodePlain(randomBytes);
                Console.WriteLine($"Bytes: {string.Concat(randomBytes.Select(b => b.ToString("X2")))} Byte length: {bigIntByteArray.Length}, {base58String}");
            }
        }
Beispiel #3
0
            public API_History_4_3(SealedTransaction T)
            {
                id           = ConvertTransactionId(T.Id);
                source       = Base58CheckEncoding.EncodePlain(T.Trxn.Source);
                target       = Base58CheckEncoding.EncodePlain(T.Trxn.Target);
                amount       = BcToDouble(T.Trxn.Amount);
                fee          = BcFeeConvert(T.Trxn.Fee.Commission);
                timeCreation = new DateTime(T.Trxn.TimeCreation);
                userFields   = T.Trxn.UserFields;
                type         = (API_TransactionType)T.Trxn.Type;

                if (T.Trxn.ExtraFee != null)
                {
                    extraFee = T.Trxn.ExtraFee.Select(m => (API_ExtraFee) new API_ExtraFee_4_3(m)).ToList();
                }

                if (T.Trxn.SmartContract != null)
                {
                    smartContract = new API_SmartContract_4_3(T.Trxn.SmartContract);
                }

                if (T.Trxn.SmartInfo != null)
                {
                    smartInfo = new API_SmartTransInfo_4_3(T.Trxn.SmartInfo);
                }
            }
        public string ToAddressString(string addressPrefix = null)
        {
            if (addressPrefix.IsNull())
            {
                addressPrefix = ChainConfig.AddressPrefix;
            }
            var buffer = ToBuffer(true);
            var hash   = SHA512.Create().HashAndDispose(buffer);

            buffer.Clear();
            var firstChecksum = RIPEMD160.Create().HashAndDispose(hash);

            hash.Clear();
            var secondChecksum = RIPEMD160.Create().HashAndDispose(firstChecksum);
            var checksum       = secondChecksum.Slice(0, 4);

            secondChecksum.Clear();
            buffer = firstChecksum.Concat(checksum);
            firstChecksum.Clear();
            checksum.Clear();
            var result = addressPrefix + Base58CheckEncoding.EncodePlain(buffer);

            buffer.Clear();
            return(result);
        }
Beispiel #5
0
        public static void Do2()
        {
            var lengths = new Dictionary <int, List <string> >();

            for (var i = 0; i < 100; i++)
            {
                var b = ByteUtils.RandomBytes(4);
                Console.WriteLine(BitConverter.ToString(b).Replace("-", string.Empty));

                var byteString = Base58CheckEncoding.EncodePlain(b);
                var length     = byteString.Length;

                // Console.WriteLine(byteString);
                if (lengths.ContainsKey(length))
                {
                    lengths[length].Append(byteString);
                }
                else
                {
                    lengths.Add(length, new List <string> {
                        byteString
                    });
                }
            }

            foreach (var v in lengths.Keys)
            {
                Console.WriteLine($"{v}: {lengths[v][0]}");
            }

            foreach (var length in lengths)
            {
                Console.WriteLine($"Kvp - [length, occurrences] {length}.");
            }
        }
Beispiel #6
0
        /// <inheritdoc/>
        public async Task <byte[]> DownloadBytesAsync(byte[] address)
        {
            if (downloadClient != null)
            {
                byte[] bytes = new byte[digestSize + 2];
                bytes[0] = fnCode;
                bytes[1] = digestSize;
                address.CopyTo(bytes, 2);
                //Encoding.Unicode.GetBytes(address, 0, address.Length, bytes, 2);

                string      hash            = Base58CheckEncoding.EncodePlain(bytes);
                RestRequest downloadRequest = new RestRequest("/ipfs/" + hash, Method.GET);
                downloadRequest.AddDecompressionMethod(System.Net.DecompressionMethods.None);

                IRestResponse response = await downloadClient.ExecuteGetTaskAsync(downloadRequest);

                if (response.ErrorException != null)
                {
                    // TODO: throw some kind of custom exception on unsuccessful upload
                    throw new Exception();
                }

                return(response.RawBytes);
            }
            return(null);
        }
 public BalanceToken BalanceTokenModel(TokenBalance model)
 {
     return(new BalanceToken
     {
         Code = model.Code,
         Token = Base58CheckEncoding.EncodePlain(model.Token),
         Balance = model.Balance
     });
 }
Beispiel #8
0
 public API_TokenTransferTransInfo_4_3(TokenTransferTransInfo I)
 {
     Code             = I.Code;
     Sender           = Base58CheckEncoding.EncodePlain(I.Sender);
     Receiver         = Base58CheckEncoding.EncodePlain(I.Receiver);
     Amount           = I.Amount;
     State            = (API_SmartOperationState)I.State;
     StateTransaction = ConvertTransactionId(I.StateTransaction);
     TransferSuccess  = I.TransferSuccess;
 }
        public void EncodePlan_And_DecodePlain_ByteString()
        {
            var bs            = ByteString.CopyFromUtf8("test byte string");
            var encodeMessage = Base58CheckEncoding.EncodePlain(bs);

            var decodeMessage = Base58CheckEncoding.DecodePlain(encodeMessage);
            var bs1           = ByteString.CopyFrom(decodeMessage);

            bs.ShouldBe(bs1);
        }
Beispiel #10
0
 public void Encode()
 {
     foreach (var tuple in _testCases)
     {
         var bytes        = tuple.Item2;
         var expectedText = tuple.Item1;
         var actualText   = Base58CheckEncoding.EncodePlain(bytes);
         Assert.AreEqual(expectedText, actualText);
     }
 }
Beispiel #11
0
 public API_TokenTransfer_4_3(TokenTransfer tt)
 {
     Token       = Base58CheckEncoding.EncodePlain(tt.Token);
     Code        = tt.Code;
     Sender      = Base58CheckEncoding.EncodePlain(tt.Sender);
     Receiver    = Base58CheckEncoding.EncodePlain(tt.Receiver);
     Amount      = tt.Amount;
     Initiator   = Base58CheckEncoding.EncodePlain(tt.Initiator);
     Transaction = ConvertTransactionId(tt.Transaction);
     Time        = tt.Time;
 }
Beispiel #12
0
        /// <summary>
        ///     Encode a publicKey into miniLock format.
        /// </summary>
        /// <param name="publicKey">A 32 byte publicKey.</param>
        /// <exception cref="Sodium.Exceptions.KeyOutOfRangeException"></exception>
        /// <returns>A Base58 encoded publicKey.</returns>
        public static string EncodeMiniLockPublicKey(byte[] publicKey)
        {
            if (publicKey == null || publicKey.Length != PublicKeyBytes)
            {
                throw new KeyOutOfRangeException("publicKey", (publicKey == null) ? 0 : publicKey.Length,
                                                 string.Format("key must be {0} bytes in length.", PublicKeyBytes));
            }

            var final = ArrayHelper.ConcatArrays(publicKey, Blake2S.Hash(publicKey, (byte[])null, 1));

            return(Base58CheckEncoding.EncodePlain(final));
        }
Beispiel #13
0
        public void EncodePlain_And_DecodePlain_Address()
        {
            var address = Address.Generate();
            var data    = address.DumpByteArray();

            var enCode = Base58CheckEncoding.EncodePlain(data);

            enCode.ShouldNotBe(string.Empty);
            var deCode = Base58CheckEncoding.DecodePlain(enCode);

            deCode.ShouldBe(data);
        }
Beispiel #14
0
        /// <summary>
        ///     Encode a publicKey into bytejail format.
        /// </summary>
        /// <param name="publicKey">A 32 byte publicKey.</param>
        /// <exception cref="KeyOutOfRangeException"></exception>
        /// <returns>A Base58 encoded publicKey.</returns>
        public static string EncodeBytejailPublicKey(byte[] publicKey)
        {
            if (publicKey == null || publicKey.Length != PublicKeyBytes)
            {
                throw new KeyOutOfRangeException("publicKey", (publicKey == null) ? 0 : publicKey.Length,
                                                 string.Format("key must be {0} bytes in length.", PublicKeyBytes));
            }

            var final = ArrayHelper.ConcatArrays(new[] { BytejailVersionPrefix }, publicKey, CalculateBytejailChecksum(new[] { BytejailVersionPrefix }, publicKey));

            return(Base58CheckEncoding.EncodePlain(final));
        }
        public void EncodePlain_And_DecodePlain_Address()
        {
            var address = Address.FromBase58("2DZER7qHVwv3PUMFsHuQaQbE4wDFsCRzJsxLwYEk8rgM3HVn1S");
            var data    = address.ToByteArray();

            var enCode = Base58CheckEncoding.EncodePlain(data);

            enCode.ShouldNotBe(string.Empty);
            var deCode = Base58CheckEncoding.DecodePlain(enCode);

            deCode.ShouldBe(data);
        }
Beispiel #16
0
        public string ToPublicKeyString(string addressPrefix = null)
        {
            if (addressPrefix.IsNull())
            {
                addressPrefix = ChainConfig.AddressPrefix;
            }
            var buffer = ToBuffer();
            var result = addressPrefix + Base58CheckEncoding.EncodePlain(buffer);

            buffer.Clear();
            return(result);
        }
Beispiel #17
0
        public void Encode(byte[] value, string fileName)
        {
            string newValue = Base58CheckEncoding.EncodePlain(value);

            var result = new FileStream(fileName + Extension, FileMode.Create);

            using (var writer = new StreamWriter(result))
            {
                writer.Write(newValue);
            }

            result.Close();
        }
        public void TestInvalidChecksum()
        {
            byte[]     expected_result = UTF8Encoding.UTF8.GetBytes("hello world");
            string     header          = "header-part ";
            string     footer          = " footer part.";
            string     encoded         = header + Base58CheckEncoding.EncodePlain(expected_result) + footer;
            SimplePack packer          = new SimplePack(header, footer);

            try{
                packer.decode(encoded);
            }
            catch (System.FormatException) { return; }
            Assert.Fail(); // Did not catch no checksum, fail
        }
Beispiel #19
0
 public static void Do3()
 {
     for (var i = 0; i < 10000; i++)
     {
         var        random          = new Random();
         BigInteger randomBigInt    = random.Next(195112, 11316495);
         var        randomBytes     = new byte[3];
         var        bigIntByteArray = randomBigInt.ToByteArray();
         randomBytes[0] = bigIntByteArray[2];
         randomBytes[1] = bigIntByteArray[1];
         randomBytes[2] = bigIntByteArray[0];
         var base58String = Base58CheckEncoding.EncodePlain(randomBytes);
         Console.WriteLine($"Bytes: {string.Concat(randomBytes.Select(b => b.ToString("X2")))} Byte length: {randomBytes.Length}, {base58String}");
     }
 }
Beispiel #20
0
 public static void Do4()
 {
     for (var i = 195112; i < 11316496; i++)
     {
         BigInteger randomBigInt    = i;
         var        randomBytes     = new byte[3];
         var        bigIntByteArray = randomBigInt.ToByteArray();
         randomBytes[0] = bigIntByteArray[2];
         randomBytes[1] = bigIntByteArray[1];
         randomBytes[2] = bigIntByteArray[0];
         var base58String = Base58CheckEncoding.EncodePlain(randomBytes);
         if (base58String.Length != 4)
         {
             Console.WriteLine($"Bytes: {string.Concat(randomBytes.Select(b => b.ToString("X2")))} Byte length: {randomBytes.Length}, {base58String}");
         }
     }
 }
        public void EncodePlain_And_DecodePlain_Hash()
        {
            var hash  = HashHelper.ComputeFrom("hash");
            var data  = hash.ToByteArray();
            var bytes = new byte[] { 0 };

            var enCode = Base58CheckEncoding.EncodePlain(data);

            enCode.ShouldNotBe(string.Empty);
            var deCode = Base58CheckEncoding.DecodePlain(enCode);

            deCode.ShouldBe(data);

            Base58CheckEncoding.EncodePlain(bytes).ShouldBe("1");
            Should.Throw <FormatException>(() => {
                Base58CheckEncoding.DecodePlain(bytes.ToString());
            });

            Should.Throw <FormatException>(() => { Base58CheckEncoding.Decode(enCode); });
        }
Beispiel #22
0
        public List <WalletAllBalance> Balance(byte[] PublicKey)
        {
            List <WalletAllBalance> Res = new List <WalletAllBalance>();

            WalletBalanceGetResult CS_Bal = CS_Balance(PublicKey);

            if (CS_Bal.Status.Code > 0)
            {
                throw new Exception(CS_Bal.Status.Message);
            }

            TokenBalancesResult Token_Balance = TokenBalance(PublicKey);

            if (Token_Balance.Status.Code > 0)
            {
                throw new Exception(Token_Balance.Status.Message);
            }

            Res.Add(WalletAllBalance.Create(BcToDouble(CS_Bal.Balance)));

            foreach (TokenBalance item in Token_Balance.Balances)
            {
                //Delete trycatch block
                try
                {
                    Res.Add(WalletAllBalance.Create(
                                Convert.ToDouble(item.Balance),
                                Base58CheckEncoding.EncodePlain(item.Token),
                                item.Code,
                                item.Name)
                            );
                }
                catch (Exception)
                {
                    Console.WriteLine("");
                }
            }

            return(Res);
        }
Beispiel #23
0
        public string ToWif()
        {
            var key = ToBuffer();
            var buffer = new byte[] { 0x80 }.Concat(key);

            key.Clear();
            var firstChecksum  = SHA256.Create().HashAndDispose(buffer);
            var secondChecksum = SHA256.Create().HashAndDispose(firstChecksum);

            firstChecksum.Clear();
            var checksum = secondChecksum.Slice(0, 4);

            secondChecksum.Clear();
            var fullBuffer = buffer.Concat(checksum);

            buffer.Clear();
            checksum.Clear();
            var wif = Base58CheckEncoding.EncodePlain(fullBuffer);

            fullBuffer.Clear();
            return(wif);
        }
Beispiel #24
0
        //  /**
        //   * Construct an empty Transaction
        //   */
        //  constructor(opts?: TransactionCtorFields)
        //        {
        //            opts && Object.assign(this, opts);
        //        }

        //        /**
        //         * Add one or more instructions to this Transaction
        //         */
        //        add(
        //    ...items: Array<
        //            Transaction | TransactionInstruction | TransactionInstructionCtorFields
        //          >

        //        ) : Transaction {
        //    if (items.length === 0) {
        //      throw new Error('No instructions');
        //    }

        //    items.forEach((item: any) => {
        //      if ('instructions' in item) {
        //        this.instructions = this.instructions.concat(item.instructions);
        //      } else if ('data' in item && 'programId' in item && 'keys' in item) {
        //        this.instructions.push(item);
        //      } else {
        //        this.instructions.push(new TransactionInstruction(item));
        //      }
        //    });
        //return this;
        //  }

        /// <summary>
        /// Compile transaction data
        /// </summary>
        /// <returns></returns>
        public Message compileMessage()
        {
            var nonceInfo = this.nonceInfo;

            if (nonceInfo != null && this.instructions[0] != nonceInfo.nonceInstruction)
            {
                this.recentBlockhash = nonceInfo.nonce;
                this.instructions.Insert(0, nonceInfo.nonceInstruction);
            }
            var recentBlockhash = this.recentBlockhash;

            if (recentBlockhash.Length < 1)
            {
                throw new Exception("Transaction recentBlockhash required");
            }

            if (this.instructions.Count < 1)
            {
                throw new Exception("No instructions provided");
            }

            PublicKey feePayer;

            if (this.feePayer != null)
            {
                feePayer = this.feePayer;
            }
            else if (signatures.Count > 0 && signatures[0].publicKey != null)
            {
                // Use implicit fee payer
                feePayer = this.signatures[0].publicKey;
            }
            else
            {
                throw new Exception("Transaction fee payer required");
            }

            for (var i = 0; i < this.instructions.Count(); i++)
            {
                if (this.instructions[i].programId == null)
                {
                    throw new Exception(string.Format("Transaction instruction index {0} has undefined program id", i));
                }
            }

            List <string>      programIds   = new List <string>();
            List <AccountMeta> accountMetas = new List <AccountMeta>();

            this.instructions.ForEach(instruction => {
                instruction.keys.ForEach(accountMeta =>
                {
                    accountMetas.Add(accountMeta);
                });

                var programId = instruction.programId.ToString();
                if (!programIds.Contains(programId))
                {
                    programIds.Add(programId);
                }
            });

            // Append programID account metas
            programIds.ForEach(programId => {
                accountMetas.Add(new AccountMeta()
                {
                    pubkey     = new PublicKey(programId),
                    isSigner   = false,
                    isWritable = false,
                });
            });

            // Sort. Prioritizing first by signer, then by writable
            accountMetas.Sort((x, y) => {
                var checkSigner   = x.isSigner == y.isSigner ? 0 : x.isSigner ? -1 : 1;
                var checkWritable = x.isWritable == y.isWritable ? 0 : x.isWritable ? -1 : 1;
                return(Convert.ToBoolean(checkSigner) ? checkSigner : checkWritable);
            });

            // Cull duplicate account metas
            List <AccountMeta> uniqueMetas = new List <AccountMeta>();

            accountMetas.ForEach(accountMeta =>
            {
                var pubkeyString = accountMeta.pubkey.ToString();
                var uniqueIndex  = uniqueMetas.FindIndex(x =>
                {
                    return(x.pubkey.ToString() == pubkeyString);
                });
                if (uniqueIndex > -1)
                {
                    var meta                 = uniqueMetas[uniqueIndex];
                    meta.isWritable          = meta.isWritable || accountMeta.isWritable;
                    uniqueMetas[uniqueIndex] = meta;
                }
                else
                {
                    uniqueMetas.Add(accountMeta);
                }
            });

            // Move fee payer to the front
            var feePayerIndex = uniqueMetas.FindIndex(x =>
            {
                return(x.pubkey.Equals(feePayer));
            });

            if (feePayerIndex > -1)
            {
                var payerMeta = uniqueMetas[feePayerIndex];
                payerMeta.isSigner   = true;
                payerMeta.isWritable = true;
                uniqueMetas.Insert(0, payerMeta);
            }
            else
            {
                uniqueMetas.Insert(0, new AccountMeta()
                {
                    pubkey     = feePayer,
                    isSigner   = true,
                    isWritable = true,
                });
            }

            // Disallow unknown signers
            foreach (var signature in this.signatures)
            {
                var uniqueIndex = uniqueMetas.FindIndex(x =>
                {
                    return(x.pubkey.Equals(signature.publicKey));
                });
                if (uniqueIndex > -1)
                {
                    if (!uniqueMetas[uniqueIndex].isSigner)
                    {
                        var meta = uniqueMetas[uniqueIndex];
                        meta.isSigner            = true;
                        uniqueMetas[uniqueIndex] = meta;
                        //console.warn(
                        //  'Transaction references a signature that is unnecessary, ' +
                        //    'only the fee payer and instruction signer accounts should sign a transaction. ' +
                        //    'This behavior is deprecated and will throw an error in the next major version release.',
                        //);
                    }
                }
                else
                {
                    throw new Exception(string.Format("unknown signer: {0}", signature.publicKey.ToString()));
                }
            }

            var numRequiredSignatures       = 0;
            var numReadonlySignedAccounts   = 0;
            var numReadonlyUnsignedAccounts = 0;

            // Split out signing from non-signing keys and count header values
            List <string> signedKeys   = new List <string>();
            List <string> unsignedKeys = new List <string>();

            uniqueMetas.ForEach(meta => {
                if (meta.isSigner)
                {
                    signedKeys.Add(meta.pubkey.ToString());
                    numRequiredSignatures += 1;
                    if (!meta.isWritable)
                    {
                        numReadonlySignedAccounts += 1;
                    }
                }
                else
                {
                    unsignedKeys.Add(meta.pubkey.ToString());
                    if (!meta.isWritable)
                    {
                        numReadonlyUnsignedAccounts += 1;
                    }
                }
            });

            signedKeys.AddRange(unsignedKeys);
            var accountKeys  = signedKeys;
            var instructions = this.instructions.Select(
                instruction =>
            {
                var data      = instruction.data;
                var programId = instruction.programId;
                //const { data, programId} = instruction;
                var cin            = new CompiledInstruction();
                cin.programIdIndex = accountKeys.IndexOf(programId.ToString());
                cin.accounts       = instruction.keys.Select(meta => accountKeys.IndexOf(meta.pubkey.ToString())).ToArray();
                cin.data           = Base58CheckEncoding.EncodePlain(data);
                return(cin);
            }).ToList();

            instructions.ForEach(instruction =>
            {
                if (!(instruction.programIdIndex >= 0))
                {
                    throw new Exception("instruction.programIdIndex error");
                }
                foreach (var keyIndex in instruction.accounts)
                {
                    if (keyIndex < 0)
                    {
                        throw new Exception("instruction.accounts error");
                    }
                }
            });
            var args = new MessageArgs()
            {
                header = new MessageHeader()
                {
                    numRequiredSignatures       = numRequiredSignatures,
                    numReadonlySignedAccounts   = numReadonlySignedAccounts,
                    numReadonlyUnsignedAccounts = numReadonlyUnsignedAccounts
                },
                accountKeys     = accountKeys.ToArray(),
                recentBlockhash = recentBlockhash,
                instructions    = instructions.ToArray()
            };

            return(new Message(args));
        }
Beispiel #25
0
 public override string ToString()
 {
     return(Base58CheckEncoding.EncodePlain(bytes));
 }