diff --git a/adnl/adnl.go b/adnl/adnl.go index 243e8523..8f1f7472 100644 --- a/adnl/adnl.go +++ b/adnl/adnl.go @@ -598,7 +598,7 @@ func (a *ADNL) GetAddressList() address.List { } func (a *ADNL) GetID() []byte { - id, _ := ToKeyID(PublicKeyED25519{Key: a.peerKey}) + id, _ := tl.Hash(PublicKeyED25519{Key: a.peerKey}) return id } @@ -639,7 +639,7 @@ func (a *ADNL) createPacket(seqno int64, isResp bool, msgs ...any) ([]byte, erro if !isResp { packet.From = &PublicKeyED25519{Key: a.ourKey.Public().(ed25519.PublicKey)} } else { - packet.FromIDShort, err = ToKeyID(PublicKeyED25519{Key: a.ourKey.Public().(ed25519.PublicKey)}) + packet.FromIDShort, err = tl.Hash(PublicKeyED25519{Key: a.ourKey.Public().(ed25519.PublicKey)}) if err != nil { return nil, err } @@ -675,7 +675,7 @@ func (a *ADNL) createPacket(seqno int64, isResp bool, msgs ...any) ([]byte, erro return nil, err } - enc, err := ToKeyID(PublicKeyED25519{Key: a.peerKey}) + enc, err := tl.Hash(PublicKeyED25519{Key: a.peerKey}) if err != nil { return nil, err } diff --git a/adnl/channel.go b/adnl/channel.go index 605b83f8..5288fe16 100644 --- a/adnl/channel.go +++ b/adnl/channel.go @@ -61,12 +61,12 @@ func (c *Channel) setup(theirKey ed25519.PublicKey) (err error) { c.encKey[(len(c.decKey)-1)-i] = c.decKey[i] } - theirID, err := ToKeyID(PublicKeyED25519{c.adnl.peerKey}) + theirID, err := tl.Hash(PublicKeyED25519{c.adnl.peerKey}) if err != nil { return err } - ourID, err := ToKeyID(PublicKeyED25519{c.adnl.ourKey.Public().(ed25519.PublicKey)}) + ourID, err := tl.Hash(PublicKeyED25519{c.adnl.ourKey.Public().(ed25519.PublicKey)}) if err != nil { return err } @@ -78,7 +78,7 @@ func (c *Channel) setup(theirKey ed25519.PublicKey) (err error) { c.encKey = c.decKey } - c.id, err = ToKeyID(PublicKeyAES{Key: c.decKey}) + c.id, err = tl.Hash(PublicKeyAES{Key: c.decKey}) if err != nil { return err } @@ -129,7 +129,7 @@ func (c *Channel) createPacket(seqno int64, msgs ...any) ([]byte, error) { ctr.XORKeyStream(packetData, packetData) - enc, err := ToKeyID(PublicKeyAES{Key: c.encKey}) + enc, err := tl.Hash(PublicKeyAES{Key: c.encKey}) if err != nil { return nil, err } diff --git a/adnl/client.go b/adnl/client.go index 76348ac1..028ad913 100644 --- a/adnl/client.go +++ b/adnl/client.go @@ -85,7 +85,7 @@ func listenPacketsAsClient(a *ADNL, conn net.Conn) error { a.Close() }() - rootID, err := ToKeyID(PublicKeyED25519{Key: a.ourKey.Public().(ed25519.PublicKey)}) + rootID, err := tl.Hash(PublicKeyED25519{Key: a.ourKey.Public().(ed25519.PublicKey)}) if err != nil { return err } diff --git a/adnl/gateway.go b/adnl/gateway.go index 7b7a6169..546a1061 100644 --- a/adnl/gateway.go +++ b/adnl/gateway.go @@ -134,7 +134,7 @@ func (g *Gateway) StartServer(listenAddr string) (err error) { return err } - rootId, err := ToKeyID(PublicKeyED25519{Key: g.key.Public().(ed25519.PublicKey)}) + rootId, err := tl.Hash(PublicKeyED25519{Key: g.key.Public().(ed25519.PublicKey)}) if err != nil { return err } @@ -168,7 +168,7 @@ func (g *Gateway) StartClient() (err error) { return err } - rootId, err := ToKeyID(PublicKeyED25519{Key: g.key.Public().(ed25519.PublicKey)}) + rootId, err := tl.Hash(PublicKeyED25519{Key: g.key.Public().(ed25519.PublicKey)}) if err != nil { return err } @@ -236,7 +236,7 @@ func (g *Gateway) listen(rootId []byte) { continue } - peerId, err = ToKeyID(PublicKeyED25519{Key: packet.From.Key}) + peerId, err = tl.Hash(PublicKeyED25519{Key: packet.From.Key}) if err != nil { // invalid packet continue @@ -402,7 +402,7 @@ func (g *Gateway) RegisterClient(addr string, key ed25519.PublicKey) (Peer, erro } udpAddr := net.UDPAddrFromAddrPort(pAddr) - clientId, err := ToKeyID(PublicKeyED25519{Key: key}) + clientId, err := tl.Hash(PublicKeyED25519{Key: key}) if err != nil { return nil, err } @@ -449,7 +449,7 @@ func (g *Gateway) write(deadline time.Time, addr net.Addr, buf []byte) error { } func (g *Gateway) GetID() []byte { - id, _ := ToKeyID(PublicKeyED25519{Key: g.key.Public().(ed25519.PublicKey)}) + id, _ := tl.Hash(PublicKeyED25519{Key: g.key.Public().(ed25519.PublicKey)}) return id } diff --git a/adnl/rldp/raptorq/solver_test.go b/adnl/rldp/raptorq/solver_test.go index 9db3e620..e287b1fa 100644 --- a/adnl/rldp/raptorq/solver_test.go +++ b/adnl/rldp/raptorq/solver_test.go @@ -2,8 +2,9 @@ package raptorq import ( "bytes" + "crypto/rand" + "encoding/binary" "encoding/hex" - "math/rand" "testing" ) @@ -58,11 +59,17 @@ func Test_EncodeDecode(t *testing.T) { } func Test_EncodeDecodeFuzz(t *testing.T) { - for n := 0; n < 100; n++ { + for n := 0; n < 1000; n++ { str := make([]byte, 4096) - rand.Read(str) + _, _ = rand.Read(str) + + buf := make([]byte, 4) + if _, err := rand.Read(buf); err != nil { + panic(err) + } + rnd := binary.LittleEndian.Uint32(buf) - symSz := (1 + (rand.Uint32() % 10)) * 10 + symSz := (1 + (rnd % 10)) * 10 r := NewRaptorQ(symSz) enc, err := r.CreateEncoder(str) if err != nil { diff --git a/example/send-to-contract/main.go b/example/send-to-contract/main.go index fc76a8c9..8857e128 100644 --- a/example/send-to-contract/main.go +++ b/example/send-to-contract/main.go @@ -53,7 +53,7 @@ func main() { if balance.Nano().Uint64() >= 3000000 { // create transaction body cell, depends on what contract needs, just random example here body := cell.BeginCell(). - MustStoreUInt(0x123abc55, 32). // op code + MustStoreUInt(0x123abc55, 32). // op code MustStoreUInt(rand.Uint64(), 64). // query id // payload: MustStoreAddr(address.MustParseAddr("EQAbMQzuuGiCne0R7QEj9nrXsjM7gNjeVmrlBZouyC-SCLlO")). diff --git a/tlb/coins_test.go b/tlb/coins_test.go index 0081c707..b2a0dfa2 100644 --- a/tlb/coins_test.go +++ b/tlb/coins_test.go @@ -1,9 +1,9 @@ package tlb import ( + "crypto/rand" "fmt" "math/big" - "math/rand" "strings" "testing" ) @@ -113,13 +113,19 @@ func TestCoins_Decimals(t *testing.T) { t.Run("decimals "+fmt.Sprint(i), func(t *testing.T) { for x := 0; x < 5000; x++ { rnd := make([]byte, 64) - rand.Read(rnd) + _, _ = rand.Read(rnd) lo := new(big.Int).Mod(new(big.Int).SetBytes(rnd), new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(i)), nil)) if i > 0 && strings.HasSuffix(lo.String(), "0") { lo = lo.Add(lo, big.NewInt(1)) } - hi := big.NewInt(rand.Int63()) + + buf := make([]byte, 8) + if _, err := rand.Read(buf); err != nil { + panic(err) + } + + hi := new(big.Int).SetBytes(buf) amt := new(big.Int).Mul(hi, new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(i)), nil)) amt = amt.Add(amt, lo) diff --git a/ton/dns/resolve.go b/ton/dns/resolve.go index 73848813..2dba6d2b 100644 --- a/ton/dns/resolve.go +++ b/ton/dns/resolve.go @@ -2,9 +2,10 @@ package dns import ( "context" + "crypto/rand" "crypto/sha256" + "encoding/binary" "fmt" - "math/rand" "strings" "github.com/xssnick/tonutils-go/address" @@ -37,7 +38,11 @@ type Client struct { api TonApi } -var randomizer = rand.Uint64 +var randomizer = func() uint64 { + buf := make([]byte, 8) + _, _ = rand.Read(buf) + return binary.LittleEndian.Uint64(buf) +} func RootContractAddr(api TonApi) (*address.Address, error) { b, err := api.CurrentMasterchainInfo(context.Background()) diff --git a/ton/dns/resolve_test.go b/ton/dns/resolve_test.go index c17ff572..58c51fb4 100644 --- a/ton/dns/resolve_test.go +++ b/ton/dns/resolve_test.go @@ -2,10 +2,10 @@ package dns import ( "bytes" + "crypto/rand" "crypto/sha256" "github.com/xssnick/tonutils-go/address" "github.com/xssnick/tonutils-go/tvm/cell" - "math/rand" "testing" ) diff --git a/ton/jetton/wallet.go b/ton/jetton/wallet.go index 2ce83414..c49ad396 100644 --- a/ton/jetton/wallet.go +++ b/ton/jetton/wallet.go @@ -2,9 +2,10 @@ package jetton import ( "context" + "crypto/rand" + "encoding/binary" "fmt" "math/big" - "math/rand" "github.com/xssnick/tonutils-go/address" "github.com/xssnick/tonutils-go/tlb" @@ -70,8 +71,14 @@ func (c *WalletClient) BuildTransferPayload(to *address.Address, amountCoins, am payloadForward = cell.BeginCell().EndCell() } + buf := make([]byte, 8) + if _, err := rand.Read(buf); err != nil { + return nil, err + } + rnd := binary.LittleEndian.Uint64(buf) + body, err := tlb.ToCell(TransferPayload{ - QueryID: rand.Uint64(), + QueryID: rnd, Amount: amountCoins, Destination: to, ResponseDestination: to, @@ -87,8 +94,14 @@ func (c *WalletClient) BuildTransferPayload(to *address.Address, amountCoins, am } func (c *WalletClient) BuildBurnPayload(amountCoins tlb.Coins, notifyAddr *address.Address) (*cell.Cell, error) { + buf := make([]byte, 8) + if _, err := rand.Read(buf); err != nil { + return nil, err + } + rnd := binary.LittleEndian.Uint64(buf) + body, err := tlb.ToCell(BurnPayload{ - QueryID: rand.Uint64(), + QueryID: rnd, Amount: amountCoins, ResponseDestination: notifyAddr, CustomPayload: nil, diff --git a/ton/nft/collection.go b/ton/nft/collection.go index e3c5cb9f..9891b230 100644 --- a/ton/nft/collection.go +++ b/ton/nft/collection.go @@ -2,9 +2,10 @@ package nft import ( "context" + "crypto/rand" + "encoding/binary" "fmt" "math/big" - "math/rand" "github.com/xssnick/tonutils-go/ton" @@ -211,8 +212,14 @@ func (c *CollectionClient) BuildMintPayload(index *big.Int, owner *address.Addre con = cell.BeginCell().MustStoreAddr(owner).MustStoreRef(con).EndCell() + buf := make([]byte, 8) + if _, err := rand.Read(buf); err != nil { + return nil, err + } + rnd := binary.LittleEndian.Uint64(buf) + body, err := tlb.ToCell(ItemMintPayload{ - QueryID: rand.Uint64(), + QueryID: rnd, Index: index, TonAmount: amountForward, Content: con, @@ -232,8 +239,14 @@ func (c *CollectionClient) BuildMintEditablePayload(index *big.Int, owner, edito con = cell.BeginCell().MustStoreAddr(owner).MustStoreRef(con).MustStoreAddr(editor).EndCell() + buf := make([]byte, 8) + if _, err := rand.Read(buf); err != nil { + return nil, err + } + rnd := binary.LittleEndian.Uint64(buf) + body, err := tlb.ToCell(ItemMintPayload{ - QueryID: rand.Uint64(), + QueryID: rnd, Index: index, TonAmount: amountForward, Content: con, diff --git a/ton/nft/item-editable.go b/ton/nft/item-editable.go index 80eafdea..008d19b0 100644 --- a/ton/nft/item-editable.go +++ b/ton/nft/item-editable.go @@ -2,9 +2,10 @@ package nft import ( "context" + "crypto/rand" + "encoding/binary" "fmt" "github.com/xssnick/tonutils-go/ton" - "math/rand" "github.com/xssnick/tonutils-go/address" "github.com/xssnick/tonutils-go/tlb" @@ -68,8 +69,14 @@ func (c *ItemEditableClient) BuildEditPayload(content ContentAny) (*cell.Cell, e } } + buf := make([]byte, 8) + if _, err := rand.Read(buf); err != nil { + return nil, err + } + rnd := binary.LittleEndian.Uint64(buf) + body, err := tlb.ToCell(ItemEditPayload{ - QueryID: rand.Uint64(), + QueryID: rnd, Content: con, }) if err != nil { diff --git a/ton/nft/item.go b/ton/nft/item.go index 6c5a1306..17f306e7 100644 --- a/ton/nft/item.go +++ b/ton/nft/item.go @@ -2,10 +2,11 @@ package nft import ( "context" + "crypto/rand" + "encoding/binary" "fmt" "github.com/xssnick/tonutils-go/ton" "math/big" - "math/rand" "github.com/xssnick/tonutils-go/address" "github.com/xssnick/tonutils-go/tlb" @@ -142,8 +143,14 @@ func (c *ItemClient) BuildTransferPayload(newOwner *address.Address, amountForwa panic("only 1 response destination is allowed") } + buf := make([]byte, 8) + if _, err := rand.Read(buf); err != nil { + return nil, err + } + rnd := binary.LittleEndian.Uint64(buf) + body, err := tlb.ToCell(TransferPayload{ - QueryID: rand.Uint64(), + QueryID: rnd, NewOwner: newOwner, ResponseDestination: respTo, CustomPayload: nil, diff --git a/ton/payments/channel.go b/ton/payments/channel.go index 26c84e78..520ba9c5 100644 --- a/ton/payments/channel.go +++ b/ton/payments/channel.go @@ -4,13 +4,13 @@ import ( "bytes" "context" "crypto/ed25519" + "crypto/rand" "encoding/hex" "fmt" "github.com/xssnick/tonutils-go/address" "github.com/xssnick/tonutils-go/tlb" "github.com/xssnick/tonutils-go/ton" "github.com/xssnick/tonutils-go/tvm/cell" - "math/rand" "time" ) diff --git a/ton/wallet/integration_test.go b/ton/wallet/integration_test.go index b746aa5e..dfc85c38 100644 --- a/ton/wallet/integration_test.go +++ b/ton/wallet/integration_test.go @@ -3,10 +3,11 @@ package wallet import ( "bytes" "context" + "crypto/rand" + "encoding/binary" "encoding/hex" "fmt" "log" - "math/rand" "os" "strings" "testing" @@ -159,7 +160,11 @@ func TestWallet_DeployContract(t *testing.T) { codeBytes, _ := hex.DecodeString("b5ee9c72410104010020000114ff00f4a413f4bcf2c80b010203844003020009a1b63c43510007a0000061d2421bb1") code, _ := cell.FromBOC(codeBytes) - addr, _, block, err := w.DeployContractWaitTransaction(ctx, tlb.MustFromTON("0.005"), cell.BeginCell().EndCell(), code, cell.BeginCell().MustStoreUInt(rand.Uint64(), 64).EndCell()) + buf := make([]byte, 8) + _, _ = rand.Read(buf) + rnd := binary.LittleEndian.Uint64(buf) + + addr, _, block, err := w.DeployContractWaitTransaction(ctx, tlb.MustFromTON("0.005"), cell.BeginCell().EndCell(), code, cell.BeginCell().MustStoreUInt(rnd, 64).EndCell()) if err != nil { t.Fatal("deploy err:", err) } @@ -256,10 +261,13 @@ func randString(n int) string { "абвгдежзиклмнопрстиквфыйцэюяАБВГДЕЖЗИЙКЛМНОПРСТИЮЯЗФЫУю!№%:,.!;(!)_+" + "😱😨🍫💋💎😄🎉☠️🙈😁🙂📱😨😮🤮👿👏🤞🖕🤜👂👃👀") - rand.Seed(time.Now().UnixNano()) + buf := make([]byte, 2) + _, _ = rand.Read(buf) + rnd := binary.LittleEndian.Uint16(buf) + b := make([]rune, n) for i := range b { - b[i] = letterRunes[rand.Intn(len(letterRunes))] + b[i] = letterRunes[int(rnd)%len(letterRunes)] } return string(b) } diff --git a/ton/wallet/wallet.go b/ton/wallet/wallet.go index 4ad6c496..c6b04a52 100644 --- a/ton/wallet/wallet.go +++ b/ton/wallet/wallet.go @@ -7,14 +7,13 @@ import ( "crypto/cipher" "crypto/ed25519" "crypto/hmac" + "crypto/rand" "crypto/sha512" + "encoding/binary" "encoding/hex" - "encoding/json" "errors" "fmt" "github.com/xssnick/tonutils-go/adnl" - "math/rand" - "os" "strings" "time" @@ -94,7 +93,12 @@ func init() { } // defining some funcs this way to mock for tests -var randUint32 = rand.Uint32 +var randUint32 = func() uint32 { + buf := make([]byte, 4) + _, _ = rand.Read(buf) + return binary.LittleEndian.Uint32(buf) +} + var timeNow = time.Now var ( @@ -369,9 +373,6 @@ func (w *Wallet) sendMany(ctx context.Context, messages []*Message, waitConfirma return nil, nil, nil, err } inMsgHash = ext.Body.Hash() - println("BD", ext.Body.Dump()) - json.NewEncoder(os.Stdout).Encode(messages[0].InternalMessage) - println("------------") if err = w.api.SendExternalMessage(ctx, ext); err != nil { return nil, nil, nil, fmt.Errorf("failed to send message: %w", err) @@ -563,7 +564,7 @@ func DecryptCommentCell(commentCell *cell.Cell, sender *address.Address, ourKey enc.CryptBlocks(data, data) if data[0] > 31 { - return nil, fmt.Errorf("invalid prefix size") + return nil, fmt.Errorf("invalid prefix size %d", data[0]) } h = hmac.New(sha512.New, []byte(sender.String())) @@ -586,7 +587,12 @@ func CreateEncryptedCommentCell(text string, senderAddr *address.Address, ourKey data := []byte(text) - pfx := make([]byte, 16+(16-(len(data)%16))) + pfxSz := 16 + if len(data)%16 != 0 { + pfxSz += 16 - (len(data) % 16) + } + + pfx := make([]byte, pfxSz) pfx[0] = byte(len(pfx)) if _, err = rand.Read(pfx[1:]); err != nil { return nil, fmt.Errorf("rand gen err: %w", err) diff --git a/ton/wallet/wallet_test.go b/ton/wallet/wallet_test.go index 659f700c..353b52d9 100644 --- a/ton/wallet/wallet_test.go +++ b/ton/wallet/wallet_test.go @@ -556,39 +556,41 @@ func (w WaiterMock) GetTransaction(ctx context.Context, block *ton.BlockIDExt, a } func TestCreateEncryptedCommentCell(t *testing.T) { - pub1, priv1, err := ed25519.GenerateKey(nil) - if err != nil { - t.Fatal(err) - return - } - pub2, priv2, err := ed25519.GenerateKey(nil) - if err != nil { - t.Fatal(err) - return - } + for i := 0; i < 100; i++ { + pub1, priv1, err := ed25519.GenerateKey(nil) + if err != nil { + t.Fatal(err) + return + } + pub2, priv2, err := ed25519.GenerateKey(nil) + if err != nil { + t.Fatal(err) + return + } - msg := randString(200) - sender := address.MustParseAddr("EQC9bWZd29foipyPOGWlVNVCQzpGAjvi1rGWF7EbNcSVClpA") + msg := randString(150 + i) + sender := address.MustParseAddr("EQC9bWZd29foipyPOGWlVNVCQzpGAjvi1rGWF7EbNcSVClpA") - c, err := CreateEncryptedCommentCell(msg, sender, priv1, pub2) - if err != nil { - t.Fatal(err) - return - } + c, err := CreateEncryptedCommentCell(msg, sender, priv1, pub2) + if err != nil { + t.Fatal(err) + return + } - data, err := DecryptCommentCell(c, address.MustParseAddr("EQDnYZIpTwo9RN_84KZX3qIkLVIUJSo8d1yz1vMlKAp2uRtK"), priv2, pub1) - if err == nil || err.Error() != "incorrect msg key" { - t.Fatal("should be error incorrect msg key, but it is:", err) - return - } + data, err := DecryptCommentCell(c, address.MustParseAddr("EQDnYZIpTwo9RN_84KZX3qIkLVIUJSo8d1yz1vMlKAp2uRtK"), priv2, pub1) + if err == nil || err.Error() != "incorrect msg key" { + t.Fatal("should be error incorrect msg key, but it is:", err) + return + } - data, err = DecryptCommentCell(c, sender, priv2, pub1) - if err != nil { - t.Fatal(err) - return - } + data, err = DecryptCommentCell(c, sender, priv2, pub1) + if err != nil { + t.Fatal(err) + return + } - if string(data) != msg { - t.Fatal("incorrect result") + if string(data) != msg { + t.Fatal("incorrect result") + } } } diff --git a/tvm/cell/builder_test.go b/tvm/cell/builder_test.go index 01b10f0a..76330188 100644 --- a/tvm/cell/builder_test.go +++ b/tvm/cell/builder_test.go @@ -2,10 +2,10 @@ package cell import ( "bytes" + "crypto/rand" "encoding/hex" "fmt" "math/big" - "math/rand" "testing" ) @@ -389,8 +389,8 @@ func TestSliceFuzz(t *testing.T) { arr2 := make([]byte, 128) for i := 0; i < 500000; i++ { - sz1 := uint(rand.Uint64() % 512) - sz2 := uint(rand.Uint64() % 512) + sz1 := uint(int(arr1[0]*arr1[1]) % 512) + sz2 := uint(int(arr2[0]*arr2[1]) % 512) rand.Read(arr1) rand.Read(arr2) diff --git a/tvm/cell/dict_test.go b/tvm/cell/dict_test.go index 007dacf7..7b352e68 100644 --- a/tvm/cell/dict_test.go +++ b/tvm/cell/dict_test.go @@ -2,11 +2,11 @@ package cell import ( "bytes" + "crypto/rand" "encoding/base64" "encoding/hex" "math" "math/big" - "math/rand" "testing" "github.com/xssnick/tonutils-go/address" @@ -174,7 +174,9 @@ func TestLoadCell_DictShuffle(t *testing.T) { empty := BeginCell().EndCell() mm := NewDict(64) for i := 0; i < 500000; i++ { - mm.SetIntKey(big.NewInt(rand.Int63()), empty) + rnd := make([]byte, 8) + _, _ = rand.Read(rnd) + _ = mm.SetIntKey(new(big.Int).SetBytes(rnd), empty) } hh, _ := mm.MustToCell().BeginParse().ToDict(64)