Remove not necessary utilities under utils/, annotate network utils, use fasthex across all project

This commit is contained in:
DataHoarder 2024-04-05 17:14:37 +02:00
parent 13d2e51383
commit 355843d5a2
Signed by: DataHoarder
SSH key fingerprint: SHA256:OLTRf6Fl87G52SiR7sWLGNzlJt4WOX+tfI2yxo0z7xk
21 changed files with 61 additions and 196 deletions

View file

@ -2,11 +2,11 @@ package address
import (
"bytes"
"encoding/hex"
"git.gammaspectra.live/P2Pool/consensus/v3/monero/crypto"
"git.gammaspectra.live/P2Pool/consensus/v3/types"
"git.gammaspectra.live/P2Pool/consensus/v3/utils"
"git.gammaspectra.live/P2Pool/edwards25519"
fasthex "github.com/tmthrgd/go-hex"
"sync/atomic"
"testing"
)
@ -17,10 +17,10 @@ var testAddress = FromBase58("42HEEF3NM9cHkJoPpDhNyJHuZ6DFhdtymCohF9CwP5KPM1Mp3e
var testAddress2 = FromBase58("4AQ3YkqG2XdWsPHEgrDGdyQLq1qMMGFqWTFJfrVQW99qPmCzZKvJqzxgf5342KC17o9bchfJcUzLhVW9QgNKTYUBLg876Gt")
var testAddress3 = FromBase58("47Eqp7fsvVnPPSU4rsXrKJhyAme6LhDRZDzFky9xWsWUS9pd6FPjJCMDCNX1NnNiDzTwfbAgGMk2N6A1aucNcrkhLffta1p")
var ephemeralPubKey, _ = hex.DecodeString("20efc1310db960b0e8d22c8b85b3414fcaa1ed9aab40cf757321dd6099a62d5e")
var ephemeralPubKey, _ = fasthex.DecodeString("20efc1310db960b0e8d22c8b85b3414fcaa1ed9aab40cf757321dd6099a62d5e")
func init() {
h, _ := hex.DecodeString("74b98b1e7ce5fc50d1634f8634622395ec2a19a4698a016fedd8139df374ac00")
h, _ := fasthex.DecodeString("74b98b1e7ce5fc50d1634f8634622395ec2a19a4698a016fedd8139df374ac00")
if _, err := privateKey.SetCanonicalBytes(h); err != nil {
utils.Panic(err)
}
@ -33,7 +33,7 @@ func TestAddress(t *testing.T) {
ephemeralPublicKey := GetPublicKeyForSharedData(testAddress, sharedData)
if bytes.Compare(ephemeralPublicKey.AsSlice(), ephemeralPubKey) != 0 {
t.Fatalf("ephemeral key mismatch, expected %s, got %s", hex.EncodeToString(ephemeralPubKey), ephemeralPublicKey.String())
t.Fatalf("ephemeral key mismatch, expected %s, got %s", fasthex.EncodeToString(ephemeralPubKey), ephemeralPublicKey.String())
}
}

View file

@ -2,7 +2,6 @@ package client
import (
"context"
"encoding/hex"
"errors"
"fmt"
"git.gammaspectra.live/P2Pool/consensus/v3/monero/transaction"
@ -11,6 +10,7 @@ import (
"git.gammaspectra.live/P2Pool/go-monero/pkg/rpc"
"git.gammaspectra.live/P2Pool/go-monero/pkg/rpc/daemon"
"github.com/floatdrop/lru"
fasthex "github.com/tmthrgd/go-hex"
"sync"
"sync/atomic"
"time"
@ -123,7 +123,7 @@ func (c *Client) GetTransactions(txIds ...types.Hash) (data [][]byte, jsonTx []*
}
for _, tx := range result.Txs {
if buf, err := hex.DecodeString(tx.PrunedAsHex); err != nil {
if buf, err := fasthex.DecodeString(tx.PrunedAsHex); err != nil {
return nil, nil, err
} else {
data = append(data, buf)
@ -144,7 +144,7 @@ func (c *Client) GetCoinbaseTransaction(txId types.Hash) (*transaction.CoinbaseT
return nil, errors.New("invalid transaction count")
}
if buf, err := hex.DecodeString(result.Txs[0].PrunedAsHex); err != nil {
if buf, err := fasthex.DecodeString(result.Txs[0].PrunedAsHex); err != nil {
return nil, err
} else {
tx := &transaction.CoinbaseTransaction{}

View file

@ -3,6 +3,7 @@ package crypto
import (
"encoding/hex"
"git.gammaspectra.live/P2Pool/consensus/v3/types"
fasthex "github.com/tmthrgd/go-hex"
"os"
"path"
"runtime"
@ -82,7 +83,7 @@ func TestDeriveViewTag(t *testing.T) {
for e := range results {
derivation := PublicKeyBytes(types.MustHashFromString(e[0]))
outputIndex, _ := strconv.ParseUint(e[1], 10, 0)
result, _ := hex.DecodeString(e[2])
result, _ := fasthex.DecodeString(e[2])
viewTag := GetDerivationViewTagForOutputIndex(&derivation, outputIndex)

View file

@ -1,13 +1,13 @@
package crypto
import (
"encoding/hex"
"git.gammaspectra.live/P2Pool/edwards25519"
fasthex "github.com/tmthrgd/go-hex"
"testing"
)
func TestKeyImageRaw(t *testing.T) {
sec, _ := hex.DecodeString("981d477fb18897fa1f784c89721a9d600bf283f06b89cb018a077f41dcefef0f")
sec, _ := fasthex.DecodeString("981d477fb18897fa1f784c89721a9d600bf283f06b89cb018a077f41dcefef0f")
scalar, _ := (&edwards25519.Scalar{}).SetCanonicalBytes(sec)
keyImage := GetKeyImage(NewKeyPairFromPrivate(PrivateKeyFromScalar(scalar)))

View file

@ -3,7 +3,6 @@ package crypto
import (
"bytes"
"database/sql/driver"
"encoding/hex"
"errors"
"git.gammaspectra.live/P2Pool/consensus/v3/utils"
"git.gammaspectra.live/P2Pool/edwards25519"
@ -68,7 +67,7 @@ func (p *PrivateKeyScalar) GetDerivationCofactor(public PublicKey) PublicKey {
}
func (p *PrivateKeyScalar) String() string {
return hex.EncodeToString(p.Scalar().Bytes())
return fasthex.EncodeToString(p.Scalar().Bytes())
}
func (p *PrivateKeyScalar) UnmarshalJSON(b []byte) error {
@ -77,7 +76,7 @@ func (p *PrivateKeyScalar) UnmarshalJSON(b []byte) error {
return err
}
if buf, err := hex.DecodeString(s); err != nil {
if buf, err := fasthex.DecodeString(s); err != nil {
return err
} else {
if len(buf) != PrivateKeySize {
@ -124,7 +123,7 @@ func (k *PrivateKeyBytes) GetDerivationCofactor(public PublicKey) PublicKey {
}
func (k *PrivateKeyBytes) String() string {
return hex.EncodeToString(k.AsSlice())
return fasthex.EncodeToString(k.AsSlice())
}
func (k *PrivateKeyBytes) Scan(src any) error {
@ -205,7 +204,7 @@ func (k *PrivateKeySlice) GetDerivationCofactor(public PublicKey) PublicKey {
}
func (k *PrivateKeySlice) String() string {
return hex.EncodeToString(*k)
return fasthex.EncodeToString(*k)
}
func (k *PrivateKeySlice) Scan(src any) error {
@ -239,7 +238,7 @@ func (k *PrivateKeySlice) UnmarshalJSON(b []byte) error {
return err
}
if buf, err := hex.DecodeString(s); err != nil {
if buf, err := fasthex.DecodeString(s); err != nil {
return err
} else {
if len(buf) != PrivateKeySize {

View file

@ -3,7 +3,6 @@ package crypto
import (
"bytes"
"database/sql/driver"
"encoding/hex"
"errors"
"git.gammaspectra.live/P2Pool/consensus/v3/utils"
"git.gammaspectra.live/P2Pool/edwards25519"
@ -64,7 +63,7 @@ func PublicKeyFromPoint(point *edwards25519.Point, _ ...any) *PublicKeyPoint {
}
func (k *PublicKeyPoint) String() string {
return hex.EncodeToString(k.Point().Bytes())
return fasthex.EncodeToString(k.Point().Bytes())
}
func (k *PublicKeyPoint) UnmarshalJSON(b []byte) error {
@ -73,7 +72,7 @@ func (k *PublicKeyPoint) UnmarshalJSON(b []byte) error {
return err
}
if buf, err := hex.DecodeString(s); err != nil {
if buf, err := fasthex.DecodeString(s); err != nil {
return err
} else {
if len(buf) != PublicKeySize {
@ -107,7 +106,7 @@ func (k *PublicKeyBytes) AsPoint() *PublicKeyPoint {
}
func (k *PublicKeyBytes) String() string {
return hex.EncodeToString(k.AsSlice())
return fasthex.EncodeToString(k.AsSlice())
}
func (k *PublicKeyBytes) Scan(src any) error {
@ -175,7 +174,7 @@ func (k *PublicKeySlice) AsPoint() *PublicKeyPoint {
}
func (k *PublicKeySlice) String() string {
return hex.EncodeToString(*k)
return fasthex.EncodeToString(*k)
}
func (k *PublicKeySlice) Scan(src any) error {
@ -209,7 +208,7 @@ func (k *PublicKeySlice) UnmarshalJSON(b []byte) error {
return err
}
if buf, err := hex.DecodeString(s); err != nil {
if buf, err := fasthex.DecodeString(s); err != nil {
return err
} else {
if len(buf) != PublicKeySize {

View file

@ -5,12 +5,12 @@ package randomx
import (
"bytes"
"crypto/subtle"
"encoding/hex"
"errors"
"git.gammaspectra.live/P2Pool/consensus/v3/monero/crypto"
"git.gammaspectra.live/P2Pool/consensus/v3/types"
"git.gammaspectra.live/P2Pool/consensus/v3/utils"
"git.gammaspectra.live/P2Pool/randomx-go-bindings"
fasthex "github.com/tmthrgd/go-hex"
"runtime"
"slices"
"sync"
@ -170,7 +170,7 @@ func (h *hasherState) Init(key []byte) (err error) {
h.key = make([]byte, len(key))
copy(h.key, key)
utils.Logf("RandomX", "Initializing to seed %s", hex.EncodeToString(h.key))
utils.Logf("RandomX", "Initializing to seed %s", fasthex.EncodeToString(h.key))
if h.dataset.GoInit(h.key, uint32(runtime.NumCPU())) == false {
return errors.New("could not initialize dataset")
}
@ -182,7 +182,7 @@ func (h *hasherState) Init(key []byte) (err error) {
return err
}
utils.Logf("RandomX", "Initialized to seed %s", hex.EncodeToString(h.key))
utils.Logf("RandomX", "Initialized to seed %s", fasthex.EncodeToString(h.key))
return nil
}

View file

@ -1,10 +1,10 @@
package crypto
import (
"encoding/hex"
"git.gammaspectra.live/P2Pool/consensus/v3/monero/crypto"
"git.gammaspectra.live/P2Pool/consensus/v3/types"
"git.gammaspectra.live/P2Pool/edwards25519"
fasthex "github.com/tmthrgd/go-hex"
"os"
"path"
"runtime"
@ -16,7 +16,7 @@ func TestDeterministicTransactionPrivateKey(t *testing.T) {
expectedPrivateKey := "c93cbd34c66ba4d5b3ddcccd3f550a0169e02225c8d045bc6418dbca4819260b"
previousId, _ := types.HashFromString("b64ec18bf2dfa4658693d7f35836d212e66dee47af6f7263ab2bf00e422bcd68")
publicSpendKeyBytes, _ := hex.DecodeString("f2be6705a034f8f485ee9bc3c21b6309cd0d9dd2111441cc32753ba2bac41b6d")
publicSpendKeyBytes, _ := fasthex.DecodeString("f2be6705a034f8f485ee9bc3c21b6309cd0d9dd2111441cc32753ba2bac41b6d")
p, _ := (&edwards25519.Point{}).SetBytes(publicSpendKeyBytes)
spendPublicKey := crypto.PublicKeyFromPoint(p)

View file

@ -2,7 +2,6 @@ package mainchain
import (
"context"
"encoding/hex"
"fmt"
mainblock "git.gammaspectra.live/P2Pool/consensus/v3/monero/block"
"git.gammaspectra.live/P2Pool/consensus/v3/monero/client"
@ -15,6 +14,7 @@ import (
"git.gammaspectra.live/P2Pool/consensus/v3/types"
"git.gammaspectra.live/P2Pool/consensus/v3/utils"
"github.com/dolthub/swiss"
fasthex "github.com/tmthrgd/go-hex"
"slices"
"sync"
"sync/atomic"
@ -91,7 +91,7 @@ func (c *MainChain) Listen() error {
ViewTag: 0,
})
} else if o.ToTaggedKey != nil {
tk, _ := hex.DecodeString(o.ToTaggedKey.ViewTag)
tk, _ := fasthex.DecodeString(o.ToTaggedKey.ViewTag)
outputs = append(outputs, transaction.Output{
Index: uint64(i),
Reward: o.Amount,
@ -110,7 +110,7 @@ func (c *MainChain) Listen() error {
return
}
extraDataRaw, _ := hex.DecodeString(fullChainMain.MinerTx.Extra)
extraDataRaw, _ := fasthex.DecodeString(fullChainMain.MinerTx.Extra)
extraTags := transaction.ExtraTags{}
if err := extraTags.UnmarshalBinary(extraDataRaw); err != nil {
//TODO: err

View file

@ -2,8 +2,8 @@ package p2p
import (
"crypto/rand"
"encoding/hex"
"git.gammaspectra.live/P2Pool/consensus/v3/p2pool/sidechain"
fasthex "github.com/tmthrgd/go-hex"
"sync/atomic"
"testing"
)
@ -21,8 +21,8 @@ func TestFindChallengeSolution(t *testing.T) {
var stop atomic.Bool
if solution, hash, ok := FindChallengeSolution(handshakeChallenge, sidechain.ConsensusDefault.Id, &stop); !ok {
t.Fatalf("No solution for %s", hex.EncodeToString(handshakeChallenge[:]))
t.Fatalf("No solution for %s", fasthex.EncodeToString(handshakeChallenge[:]))
} else {
t.Logf("Solution for %s is %d (hash %s)", hex.EncodeToString(handshakeChallenge[:]), solution, hash.String())
t.Logf("Solution for %s is %d (hash %s)", fasthex.EncodeToString(handshakeChallenge[:]), solution, hash.String())
}
}

View file

@ -4,13 +4,13 @@ import (
"bufio"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"git.gammaspectra.live/P2Pool/consensus/v3/p2pool/sidechain"
p2pooltypes "git.gammaspectra.live/P2Pool/consensus/v3/p2pool/types"
"git.gammaspectra.live/P2Pool/consensus/v3/types"
"git.gammaspectra.live/P2Pool/consensus/v3/utils"
fasthex "github.com/tmthrgd/go-hex"
"io"
unsafeRandom "math/rand/v2"
"net"
@ -406,17 +406,17 @@ func (c *Client) OnConnection() {
if c.IsIncomingConnection {
if hash, ok := CalculateChallengeHash(c.handshakeChallenge, c.Owner.Consensus().Id, solution); !ok {
//not enough PoW
c.Ban(DefaultBanTime, fmt.Errorf("not enough PoW on HANDSHAKE_SOLUTION, challenge = %s, solution = %d, calculated hash = %s, expected hash = %s", hex.EncodeToString(c.handshakeChallenge[:]), solution, hash.String(), challengeHash.String()))
c.Ban(DefaultBanTime, fmt.Errorf("not enough PoW on HANDSHAKE_SOLUTION, challenge = %s, solution = %d, calculated hash = %s, expected hash = %s", fasthex.EncodeToString(c.handshakeChallenge[:]), solution, hash.String(), challengeHash.String()))
return
} else if hash != challengeHash {
//wrong hash
c.Ban(DefaultBanTime, fmt.Errorf("wrong hash HANDSHAKE_SOLUTION, challenge = %s, solution = %d, calculated hash = %s, expected hash = %s", hex.EncodeToString(c.handshakeChallenge[:]), solution, hash.String(), challengeHash.String()))
c.Ban(DefaultBanTime, fmt.Errorf("wrong hash HANDSHAKE_SOLUTION, challenge = %s, solution = %d, calculated hash = %s, expected hash = %s", fasthex.EncodeToString(c.handshakeChallenge[:]), solution, hash.String(), challengeHash.String()))
return
}
} else {
if hash, _ := CalculateChallengeHash(c.handshakeChallenge, c.Owner.Consensus().Id, solution); hash != challengeHash {
//wrong hash
c.Ban(DefaultBanTime, fmt.Errorf("wrong hash HANDSHAKE_SOLUTION, challenge = %s, solution = %d, calculated hash = %s, expected hash = %s", hex.EncodeToString(c.handshakeChallenge[:]), solution, hash.String(), challengeHash.String()))
c.Ban(DefaultBanTime, fmt.Errorf("wrong hash HANDSHAKE_SOLUTION, challenge = %s, solution = %d, calculated hash = %s, expected hash = %s", fasthex.EncodeToString(c.handshakeChallenge[:]), solution, hash.String(), challengeHash.String()))
return
}
}

View file

@ -3,7 +3,6 @@ package sidechain
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"git.gammaspectra.live/P2Pool/consensus/v3/monero"
@ -15,6 +14,7 @@ import (
p2poolcrypto "git.gammaspectra.live/P2Pool/consensus/v3/p2pool/crypto"
"git.gammaspectra.live/P2Pool/consensus/v3/types"
"git.gammaspectra.live/P2Pool/consensus/v3/utils"
fasthex "github.com/tmthrgd/go-hex"
"io"
"slices"
"sync/atomic"
@ -377,7 +377,7 @@ type FullId [FullIdSize]byte
func FullIdFromString(s string) (FullId, error) {
var h FullId
if buf, err := hex.DecodeString(s); err != nil {
if buf, err := fasthex.DecodeString(s); err != nil {
return h, err
} else {
if len(buf) != FullIdSize {
@ -401,7 +401,7 @@ func (id FullId) ExtraNonce() uint32 {
}
func (id FullId) String() string {
return hex.EncodeToString(id[:])
return fasthex.EncodeToString(id[:])
}
func (b *PoolBlock) CalculateFullId(consensus *Consensus) FullId {

View file

@ -3,8 +3,8 @@ package types
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
fasthex "github.com/tmthrgd/go-hex"
"net/netip"
)
@ -121,7 +121,7 @@ func (c SoftwareId) String() string {
var buf = [17]byte{'U', 'n', 'k', 'n', 'o', 'w', 'n', '(', 0, 0, 0, 0, 0, 0, 0, 0, ')'}
var intBuf [4]byte
binary.LittleEndian.PutUint32(intBuf[:], uint32(c))
hex.Encode(buf[8:], intBuf[:])
fasthex.Encode(buf[8:], intBuf[:])
return string(buf[:])
}
}

View file

@ -3,7 +3,6 @@ package types
import (
"bytes"
"database/sql/driver"
"encoding/hex"
"errors"
"git.gammaspectra.live/P2Pool/consensus/v3/utils"
"github.com/holiman/uint256"
@ -219,7 +218,7 @@ func MustDifficultyFromString(s string) Difficulty {
func DifficultyFromString(s string) (Difficulty, error) {
if strings.HasPrefix(s, "0x") {
if buf, err := hex.DecodeString(s[2:]); err != nil {
if buf, err := fasthex.DecodeString(s[2:]); err != nil {
return ZeroDifficulty, err
} else {
//TODO: check this
@ -228,7 +227,7 @@ func DifficultyFromString(s string) (Difficulty, error) {
return DifficultyFromBytes(d[:]), nil
}
} else {
if buf, err := hex.DecodeString(s); err != nil {
if buf, err := fasthex.DecodeString(s); err != nil {
return ZeroDifficulty, err
} else {
if len(buf) != DifficultySize {
@ -299,7 +298,7 @@ func (d Difficulty) Bytes() []byte {
}
func (d Difficulty) String() string {
return hex.EncodeToString(d.Bytes())
return fasthex.EncodeToString(d.Bytes())
}
func (d Difficulty) StringNumeric() string {

View file

@ -3,7 +3,6 @@ package types
import (
"database/sql/driver"
"encoding/binary"
"encoding/hex"
"errors"
fasthex "github.com/tmthrgd/go-hex"
"runtime"
@ -34,7 +33,7 @@ func MustHashFromString(s string) Hash {
func HashFromString(s string) (Hash, error) {
var h Hash
if buf, err := hex.DecodeString(s); err != nil {
if buf, err := fasthex.DecodeString(s); err != nil {
return h, err
} else {
if len(buf) != HashSize {
@ -93,7 +92,7 @@ func (h Hash) Compare(other Hash) int {
}
func (h Hash) String() string {
return hex.EncodeToString(h[:])
return fasthex.EncodeToString(h[:])
}
func (h Hash) Uint64() uint64 {
@ -151,7 +150,7 @@ func (b Bytes) MarshalJSON() ([]byte, error) {
}
func (b Bytes) String() string {
return hex.EncodeToString(b)
return fasthex.EncodeToString(b)
}
func (b *Bytes) UnmarshalJSON(buf []byte) error {

View file

@ -28,6 +28,9 @@ func InterfaceAddrs(ifi *net.Interface) ([]*ExtendedIPNet, error) {
// If the ifi is nil, interfaceAddrTable returns addresses for all
// network interfaces. Otherwise it returns addresses for a specific
// interface.
//
// Modified from https://github.com/golang/go/blob/a2d2e6e7cb12c57cd8f5af64909882bab1dbca19/src/net/interface_linux.go
// Adds support for ExtendedIPNet, no other changes
func interfaceAddrTable(ifi *net.Interface) ([]*ExtendedIPNet, error) {
tab, err := syscall.NetlinkRIB(syscall.RTM_GETADDR, syscall.AF_UNSPEC)
if err != nil {
@ -55,6 +58,9 @@ func interfaceAddrTable(ifi *net.Interface) ([]*ExtendedIPNet, error) {
// If the ifindex is zero, interfaceTable returns mappings of all
// network interfaces. Otherwise it returns a mapping of a specific
// interface.
//
// Modified from https://github.com/golang/go/blob/a2d2e6e7cb12c57cd8f5af64909882bab1dbca19/src/net/interface_linux.go
// Adds support for ExtendedIPNet, no other changes
func interfaceTable(ifindex int) ([]net.Interface, error) {
tab, err := syscall.NetlinkRIB(syscall.RTM_GETLINK, syscall.AF_UNSPEC)
if err != nil {
@ -87,6 +93,7 @@ loop:
return ift, nil
}
// Copied from https://github.com/golang/go/blob/a2d2e6e7cb12c57cd8f5af64909882bab1dbca19/src/net/interface.go
func interfaceByIndex(ift []net.Interface, index int) (*net.Interface, error) {
for _, ifi := range ift {
if index == ifi.Index {
@ -96,6 +103,8 @@ func interfaceByIndex(ift []net.Interface, index int) (*net.Interface, error) {
return nil, errors.New("no such network interface")
}
// Modified from https://github.com/golang/go/blob/a2d2e6e7cb12c57cd8f5af64909882bab1dbca19/src/net/interface.go
// Adds support for ExtendedIPNet, no other changes
func addrTable(ift []net.Interface, ifi *net.Interface, msgs []syscall.NetlinkMessage) ([]*ExtendedIPNet, error) {
var ifat []*ExtendedIPNet
loop:
@ -148,6 +157,9 @@ const (
)
// newAddr altered version
//
// Modified from https://github.com/golang/go/blob/a2d2e6e7cb12c57cd8f5af64909882bab1dbca19/src/net/interface_linux.go
// Adds support for ExtendedIPNet, interface address flags
func newAddr(ifam *syscall.IfAddrmsg, attrs []syscall.NetlinkRouteAttr) *ExtendedIPNet {
var ipPointToPoint bool
// Seems like we need to make sure whether the IP interface
@ -206,6 +218,7 @@ const (
sysARPHardwareGREIPv6 = 823 // any over GRE over IPv6 tunneling
)
// Copied from https://github.com/golang/go/blob/a2d2e6e7cb12c57cd8f5af64909882bab1dbca19/src/net/interface.go
func linkFlags(rawFlags uint32) net.Flags {
var f net.Flags
if rawFlags&syscall.IFF_UP != 0 {
@ -229,6 +242,7 @@ func linkFlags(rawFlags uint32) net.Flags {
return f
}
// Copied from https://github.com/golang/go/blob/a2d2e6e7cb12c57cd8f5af64909882bab1dbca19/src/net/interface.go
func newLink(ifim *syscall.IfInfomsg, attrs []syscall.NetlinkRouteAttr) *net.Interface {
ifi := &net.Interface{Index: int(ifim.Index), Flags: linkFlags(ifim.Flags)}
for _, a := range attrs {

View file

@ -1,93 +1,12 @@
package utils
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/jxskiss/base62"
fasthex "github.com/tmthrgd/go-hex"
"math/bits"
"strconv"
"strings"
)
var encoding = base62.NewEncoding("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
func DecodeBinaryNumber(i string) uint64 {
if n, err := strconv.ParseUint(i, 10, 0); strings.Index(i, ".") == -1 && err == nil {
return n
}
if n, err := encoding.ParseUint([]byte(strings.ReplaceAll(i, ".", ""))); err == nil {
return n
}
return 0
}
func EncodeBinaryNumber(n uint64) string {
v1 := string(encoding.FormatUint(n))
v2 := strconv.FormatUint(n, 10)
if !strings.ContainsAny(v1, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") {
v1 = "." + v1
}
if len(v1) >= len(v2) {
return v2
}
return v1
}
func DecodeHexBinaryNumber(i string) string {
if _, err := hex.DecodeString(i); strings.Index(i, ".") == -1 && err == nil {
return i
}
if n, err := encoding.Decode([]byte(strings.ReplaceAll(i, ".", ""))); err == nil {
return hex.EncodeToString(n)
}
return ""
}
func EncodeSliceBinaryNumber(dst, src []byte) []byte {
if len(dst) < 1+(len(src)*2) {
return nil
}
v := encoding.EncodeToBuf(dst[:0], src)
if !bytes.ContainsAny(v, "GHIJKLMNOPQRSTUVWXYZghijklmnopqrstuvwxyz") {
copy(dst[1:], v)
dst[0] = '.'
v = dst[:len(v)]
}
if len(v) >= (len(src) * 2) {
fasthex.Encode(dst, src)
return dst[:len(src)*2]
}
return v
}
func EncodeHexBinaryNumber(v2 string) string {
b, _ := hex.DecodeString(v2)
v1 := encoding.EncodeToString(b)
if !strings.ContainsAny(v1, "GHIJKLMNOPQRSTUVWXYZghijklmnopqrstuvwxyz") {
v1 = "." + v1
}
if len(v1) >= len(v2) {
return v2
}
return v1
}
func PreviousPowerOfTwo(x uint64) int {
if x == 0 {
return 0

View file

@ -4,15 +4,6 @@ import (
"testing"
)
func TestNumber(t *testing.T) {
s := "S"
n := uint64(28)
if DecodeBinaryNumber(s) != n {
t.Fail()
}
}
func TestPreviousPowerOfTwo(t *testing.T) {
loopPath := func(x uint64) int {
//find closest low power of two

View file

@ -1,21 +0,0 @@
package utils
func Shorten(value string, n int) string {
if len(value) <= n*2+3 {
return value
} else {
return value[:n] + "..." + value[len(value)-n:]
}
}
func ShortenSlice(value []byte, n int) []byte {
if len(value) <= n*2+3 {
return value
} else {
copy(value[n+3:], value[len(value)-n:])
value[n] = '.'
value[n+1] = '.'
value[n+2] = '.'
return value[:n*2+3]
}
}

View file

@ -1,35 +0,0 @@
package utils
import (
"math"
)
func ProbabilityEffort(effort float64) float64 {
return 1 - math.Exp(-effort/100)
}
func ProbabilityMode(i ...float64) (n float64) {
//cannot use max as it's not variadic
for _, item := range i {
if item > n {
n = item
}
}
return n
}
func ProbabilityNShares(shares uint64, effort float64) float64 {
num := math.Pow(effort/100, float64(shares))
den := float64(Factorial(shares))
return (num / den) * math.Exp(-effort/100)
}
// Factorial Valid for small n
func Factorial(n uint64) (result uint64) {
if n > 0 {
result = n * Factorial(n-1)
return result
}
return 1
}