Skip to content

Cryptographic Utilities

Cryptographic and hashing utility functions for Starknet development.

Function Selector Generation

GetSelectorFromName

Generates a function selector from a given function name. The selector is returned as a big.Int.

func GetSelectorFromName(funcName string) *big.Int
Parameters:
  • funcName - The name of the function
Returns:
  • *big.Int - The selector
Usage Example:
package main
 
import (
	"fmt"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Get selector for "transfer" function
	selector := utils.GetSelectorFromName("transfer")
	fmt.Printf("Transfer selector (big.Int): %s\n", selector.String())
 
	// Get selector for "balanceOf" function
	balanceSelector := utils.GetSelectorFromName("balanceOf")
	fmt.Printf("BalanceOf selector (big.Int): %s\n", balanceSelector.String())
}

GetSelectorFromNameFelt

Returns a Felt based on the given function name. This is a convenience wrapper around GetSelectorFromName that returns the selector as a Felt instead of a big.Int.

func GetSelectorFromNameFelt(funcName string) *felt.Felt
Parameters:
  • funcName - The name of the function
Returns:
  • *felt.Felt - The selector as a Felt
Usage Example:
package main
 
import (
	"context"
	"fmt"
	"log"
 
	"github.com/NethermindEth/starknet.go/rpc"
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	provider, err := rpc.NewProvider("https://starknet-sepolia.public.blastapi.io/rpc/v0_8")
	if err != nil {
		log.Fatal(err)
	}
 
	// ETH contract on Sepolia
	contractAddress, _ := utils.HexToFelt("0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7")
 
	// Get balance selector
	balanceOfSelector := utils.GetSelectorFromNameFelt("balanceOf")
 
	// Prepare account address to check balance
	accountAddress, _ := utils.HexToFelt("0x...")
 
	// Call balanceOf
	result, err := provider.Call(
		context.Background(),
		rpc.FunctionCall{
			ContractAddress:    contractAddress,
			EntryPointSelector: balanceOfSelector,
			Calldata:           []*felt.Felt{accountAddress},
		},
		rpc.BlockID{Tag: "latest"},
	)
	if err != nil {
		log.Fatal(err)
	}
 
	fmt.Printf("Balance: %s\n", result[0])
}

Hashing Functions

Keccak256

Returns the Keccak-256 hash of the input data.

Reference: Ethereum go-ethereum crypto implementation

func Keccak256(data ...[]byte) []byte
Parameters:
  • data - A variadic parameter of type []byte representing the input data
Returns:
  • []byte - A 32-byte hash output
Usage Example:
package main
 
import (
	"encoding/hex"
	"fmt"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Hash a single byte array
	input := []byte("Hello, Starknet!")
	hash := utils.Keccak256(input)
	fmt.Printf("Keccak256 hash: 0x%s\n", hex.EncodeToString(hash))
 
	// Hash multiple byte arrays
	part1 := []byte("Hello, ")
	part2 := []byte("Starknet!")
	combinedHash := utils.Keccak256(part1, part2)
	fmt.Printf("Combined hash: 0x%s\n", hex.EncodeToString(combinedHash))
}

NewKeccakState

Returns a new instance of KeccakState. This is useful for incremental hashing operations.

Reference: Ethereum go-ethereum crypto implementation

func NewKeccakState() KeccakState
Parameters:
  • None
Returns:
  • KeccakState - A new instance of KeccakState
Usage Example:
package main
 
import (
	"encoding/hex"
	"fmt"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Create new Keccak state
	state := utils.NewKeccakState()
 
	// Write data incrementally
	state.Write([]byte("Hello, "))
	state.Write([]byte("Starknet!"))
 
	// Get hash
	hash := state.Sum(nil)
	fmt.Printf("Incremental hash: 0x%s\n", hex.EncodeToString(hash))
 
	// Reset and hash something else
	state.Reset()
	state.Write([]byte("New data"))
	newHash := state.Sum(nil)
	fmt.Printf("New hash: 0x%s\n", hex.EncodeToString(newHash))
}

Cryptographic Operations

ComputeFact

Computes the fact hash for a program and its outputs. This is used in Starknet's fact registry system.

func ComputeFact(programHash *big.Int, programOutputs []*big.Int) *big.Int
Parameters:
  • programHash - A pointer to a big.Int representing the program hash
  • programOutputs - A slice of pointers to big.Int representing the program outputs
Returns:
  • *big.Int - A pointer to a big.Int representing the computed fact
Usage Example:
package main
 
import (
	"fmt"
	"math/big"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Program hash
	programHash := big.NewInt(12345)
 
	// Program outputs
	outputs := []*big.Int{
		big.NewInt(100),
		big.NewInt(200),
		big.NewInt(300),
	}
 
	// Compute fact
	fact := utils.ComputeFact(programHash, outputs)
	fmt.Printf("Computed fact: %s\n", fact.String())
	fmt.Printf("Fact hex: %s\n", utils.BigToHex(fact))
}

MaskBits

Masks (excess) bits in a slice of bytes based on the given mask and word size.

func MaskBits(mask, wordSize int, slice []byte) []byte
Parameters:
  • mask - An integer representing the number of bits to mask
  • wordSize - An integer representing the size of each word in bits
  • slice - A slice of bytes to mask
Returns:
  • []byte - A slice of bytes with the masked bits
Usage Example:
package main
 
import (
	"encoding/hex"
	"fmt"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Sample byte slice
	data := []byte{0xFF, 0xFF, 0xFF, 0xFF}
 
	// Mask 16 bits with word size 8
	masked := utils.MaskBits(16, 8, data)
	fmt.Printf("Original: 0x%s\n", hex.EncodeToString(data))
	fmt.Printf("Masked: 0x%s\n", hex.EncodeToString(masked))
}

Fact String Utilities

SplitFactStr

Splits a given fact (with maximum 256 bits size) into two parts: fact_low and fact_high.

The function takes a fact string as input, converts it to a big number, and splits it into low (last 16 bytes) and high (first 16 bytes) parts. Each part is returned as a hexadecimal string.

func SplitFactStr(fact string) (factLow, factHigh string, err error)
Parameters:
  • fact - The fact string to be split
Returns:
  • factLow - The low part of the fact string in hexadecimal format
  • factHigh - The high part of the fact string in hexadecimal format
  • error - An error if any
Usage Example:
package main
 
import (
	"fmt"
	"log"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Example fact (256-bit value)
	fact := "0x123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0"
 
	// Split the fact
	low, high, err := utils.SplitFactStr(fact)
	if err != nil {
		log.Fatal(err)
	}
 
	fmt.Printf("Original fact: %s\n", fact)
	fmt.Printf("Fact low: %s\n", low)
	fmt.Printf("Fact high: %s\n", high)
}

FmtKecBytes

Formats the given big.Int as a byte slice (Keccak hash) with a specified length. If the length of the buffer is less than the specified length, the function pads the buffer with zeros.

func FmtKecBytes(in *big.Int, rolen int) []byte
Parameters:
  • in - The big.Int to be formatted
  • rolen - The length of the buffer
Returns:
  • []byte - The formatted buffer
Usage Example:
package main
 
import (
	"encoding/hex"
	"fmt"
	"math/big"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Create a big.Int value
	value := big.NewInt(12345)
 
	// Format to 32 bytes
	formatted := utils.FmtKecBytes(value, 32)
	fmt.Printf("Formatted (32 bytes): 0x%s\n", hex.EncodeToString(formatted))
 
	// Format to 64 bytes
	formatted64 := utils.FmtKecBytes(value, 64)
	fmt.Printf("Formatted (64 bytes): 0x%s\n", hex.EncodeToString(formatted64))
}

String Conversion Utilities

UTF8StrToBig

Converts a UTF-8 string to a big integer.

func UTF8StrToBig(str string) *big.Int
Parameters:
  • str - The UTF-8 string to convert to a big integer
Returns:
  • *big.Int - A pointer to a big.Int representing the converted value
Usage Example:
package main
 
import (
	"fmt"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Convert UTF-8 string to big.Int
	str := "Hello"
	bigNum := utils.UTF8StrToBig(str)
	fmt.Printf("String: %s\n", str)
	fmt.Printf("Big.Int: %s\n", bigNum.String())
	fmt.Printf("Hex: %s\n", utils.BigToHex(bigNum))
}

StrToBig

Generates a big.Int from a string representation.

func StrToBig(str string) *big.Int
Parameters:
  • str - The string to convert to a big.Int
Returns:
  • *big.Int - A pointer to a big.Int representing the converted value
Usage Example:
package main
 
import (
	"fmt"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Convert numeric string to big.Int
	str := "123456789012345678901234567890"
	bigNum := utils.StrToBig(str)
	fmt.Printf("String: %s\n", str)
	fmt.Printf("Big.Int: %s\n", bigNum.String())
}

StrToHex

Generates a hexadecimal representation from a string/number.

func StrToHex(str string) string
Parameters:
  • str - The string to convert to a hexadecimal
Returns:
  • string - A string representing the hexadecimal value
Usage Example:
package main
 
import (
	"fmt"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Convert string to hex
	str := "Hello"
	hex := utils.StrToHex(str)
	fmt.Printf("String: %s\n", str)
	fmt.Printf("Hex: %s\n", hex)
}

SNValToBN

Converts a given string to a big.Int by checking if the string contains a "0x" prefix. This is used in string conversions when interfacing with the Starknet APIs.

func SNValToBN(str string) *big.Int
Parameters:
  • str - A string to be converted to big.Int
Returns:
  • *big.Int - A pointer to a big.Int representing the converted value
Usage Example:
package main
 
import (
	"fmt"
 
	"github.com/NethermindEth/starknet.go/utils"
)
 
func main() {
	// Convert hex string with prefix
	hexStr := "0x1234"
	bigNum1 := utils.SNValToBN(hexStr)
	fmt.Printf("Hex string: %s -> %s\n", hexStr, bigNum1.String())
 
	// Convert numeric string
	numStr := "4660"
	bigNum2 := utils.SNValToBN(numStr)
	fmt.Printf("Numeric string: %s -> %s\n", numStr, bigNum2.String())
}

Related