massalib

package module
v0.0.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 24, 2026 License: MIT Imports: 19 Imported by: 0

README

massalib

Tests Coverage Status Go Reference

Go library for interacting with the Massa blockchain. Provides address encoding/decoding, public key handling, operation construction and signing, and a gRPC client for communicating with Massa nodes.

Install

go get github.com/KarpelesLab/massalib

Features

  • Addresses — Decode, encode, and derive Massa addresses (user AU and smart contract AS prefixes) with base58check validation
  • Public keys — Parse, serialize, and convert Ed25519 public keys to addresses
  • Operations — Build, sign, hash, and serialize Massa operations (transfers, roll buy/sell, smart contract execute/call)
  • gRPC client — Connect to a Massa node and query status, stream slot transfers, and submit operations
  • Chain IDs — Constants for MainNet, BuildNet, SecureNet, LabNet, and Sandbox

Usage

Decode an address
addr, err := massalib.DecodeAddress("AU128qq86hv2NzXqhowRzaeMruThQyxQQC3PgW3cgHg2ttgXMTa1A")
if err != nil {
    log.Fatal(err)
}
fmt.Println(addr.Thread()) // blockclique thread (0–31)
Parse a public key and derive its address
pk := &massalib.PublicKey{}
err := pk.UnmarshalText([]byte("P1t4JZwHhWNLt4xYabCbukyVNxSbhYPdF6wCYuRmDuHD784juxd"))
if err != nil {
    log.Fatal(err)
}
addr := pk.AsAddress()
fmt.Println(addr) // AU1zyQ2XEA6ZCCtR3CDQVRC7Q1rBpNZDmQe1EN5FXrQCq9435ziH
Build and sign a transaction
dest, _ := massalib.DecodeAddress("AU128qq86hv2NzXqhowRzaeMruThQyxQQC3PgW3cgHg2ttgXMTa1A")

op := &massalib.Operation{
    Fee:    1000,
    Expire: currentPeriod + 10,
    Body: &massalib.BodyTransaction{
        Destination: dest,
        Amount:      1_000_000_000, // 1 MAS
    },
}

signed, err := op.Sign(massalib.MainNet, privateKey)
if err != nil {
    log.Fatal(err)
}
Connect to a node via gRPC
import (
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"
)

rpc, err := massalib.New("localhost:33037",
    grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
    log.Fatal(err)
}
defer rpc.Close()

status, err := rpc.GetStatus(context.Background())
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Node %s running %s\n", status.NodeId, status.Version)
Submit operations
ids, err := rpc.SendOperations(ctx, signed)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Operation IDs:", ids)

Types

Type Description
Address Massa address (user or smart contract) with base58check encoding
PublicKey Ed25519 public key with version prefix
Amount Coin amount as uint64 with 9 decimal places (max ~18.4B MAS)
ChainId Network identifier (MainNet, BuildNet, etc.)
Operation Fee + expiry + typed body
BodyTransaction MAS transfer
BodyRollBuy / BodyRollSell Staking roll operations
BodyExecuteSC Smart contract bytecode execution
BodyCallSC Smart contract function call
RPC gRPC client wrapper

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeProtobufVarint

func DecodeProtobufVarint(buf []byte) (result uint64, buflen int, err error)

DecodeProtobufVarint decodes a varint encoded following protobuf conventions from the given byte slice. It returns the decoded value, the number of bytes consumed, and any error encountered.

func EncodeProtobufVarint

func EncodeProtobufVarint(x uint64) []byte

EncodeProtobufVarint encodes the given integer using protobuf varint conventions.

func ReadProtobufVarint

func ReadProtobufVarint(r bytereader) (uint64, int64, error)

ReadProtobufVarint reads a protobuf varint from the given reader. It returns the decoded value, the number of bytes read, and any error encountered.

Types

type Address

type Address struct {
	Category uint64 // 0 for User, 1 for Smart contract
	Version  uint64
	Hash     []byte // Underlying blake3 hash
}

Address represents a Massa blockchain address, which can be either a user account (Category 0) or a smart contract (Category 1).

See: https://docs.massa.net/docs/learn/operation-format-execution#address

func DecodeAddress

func DecodeAddress(addr string) (*Address, error)

DecodeAddress parses a Massa address string (AU for user, AS for smart contract) or a public key string (P prefix) into an Address. It validates the base58check checksum and returns an error if the address is malformed.

func (*Address) Bytes

func (a *Address) Bytes() []byte

Bytes encodes the address in massa byte format.

func (*Address) MarshalBinary

func (a *Address) MarshalBinary() ([]byte, error)

MarshalBinary encodes the address in massa byte format (for compatibility).

func (*Address) ReadFrom

func (a *Address) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads a binary address from a given source, which is made of two varint (category, version) followed by 32 bytes of hash.

func (*Address) SetValue

func (a *Address) SetValue(in []byte)

SetValue computes the hash of the provided buffer and sets it as address Hash.

func (*Address) String

func (a *Address) String() string

String encodes the address as a string following Massa encoding conventions.

func (*Address) Thread

func (a *Address) Thread() byte

Thread returns the blockclique sharding thread of the address, computed by taking the first 5 bits of the underlying hash.

type Amount

type Amount uint64

Amount represents a Massa coin amount as a uint64 with 9 decimal places of precision. The maximum representable amount is 18,446,744,073.709551615 MAS.

See: https://docs.massa.net/docs/learn/operation-format-execution#coin-amounts

func (Amount) Bytes

func (a Amount) Bytes() []byte

Bytes returns the protobuf varint encoding of the amount.

func (*Amount) ReadFrom

func (a *Amount) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads a varint-encoded amount from the given reader.

type BodyCallSC

type BodyCallSC struct {
	MaxGas   uint64
	MaxCoins Amount
	Target   *Address
	Function string // Name of the function to call encoded as UTF-8 string
	Param    []byte
}

BodyCallSC represents a smart contract function call operation.

type BodyExecuteSC

type BodyExecuteSC struct {
	MaxGas    uint64
	MaxCoins  Amount
	Bytecode  []byte           // Raw bytes of bytecode to execute (up to 10MB)
	Datastore []*DataStoreItem // Concatenated datastore items
}

BodyExecuteSC represents a smart contract execution operation.

type BodyRollBuy

type BodyRollBuy struct {
	Rolls uint64
}

BodyRollBuy represents a roll purchase operation for staking.

type BodyRollSell

type BodyRollSell struct {
	Rolls uint64
}

BodyRollSell represents a roll sale operation.

type BodyTransaction

type BodyTransaction struct {
	Destination *Address
	Amount      Amount
}

BodyTransaction represents a MAS coin transfer operation.

func (*BodyTransaction) Bytes

func (tx *BodyTransaction) Bytes() []byte

Bytes returns the binary encoding of the transaction body.

func (*BodyTransaction) ReadFrom

func (tx *BodyTransaction) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads a transaction body from the given reader.

func (*BodyTransaction) Type

func (tx *BodyTransaction) Type() OperationType

Type returns OpTransaction.

func (*BodyTransaction) UnmarshalBinary

func (tx *BodyTransaction) UnmarshalBinary(buf []byte) error

UnmarshalBinary decodes a transaction body from its binary representation.

type ChainId

type ChainId uint64

ChainId identifies a Massa blockchain network.

const (
	MainNet   ChainId = 77658377
	BuildNet  ChainId = 77658366
	SecureNet ChainId = 77658383
	LabNet    ChainId = 77658376
	Sandbox   ChainId = 77
)

Well-known Massa chain IDs.

func (ChainId) AppendBinary

func (c ChainId) AppendBinary(b []byte) ([]byte, error)

AppendBinary appends the big-endian 8-byte encoding of the chain ID to b.

func (ChainId) Bytes

func (c ChainId) Bytes() []byte

Bytes returns the big-endian 8-byte encoding of the chain ID.

type DataStoreItem

type DataStoreItem struct {
	Key   []byte
	Value []byte
}

DataStoreItem represents a key-value pair in a smart contract datastore.

type Operation

type Operation struct {
	Fee    Amount
	Expire uint64 // expire_period, typically current period + 10
	Body   OperationBody
}

Operation represents a Massa operation consisting of a fee, expiration period, and a typed body.

func (*Operation) Bytes

func (o *Operation) Bytes() []byte

Bytes returns the binary representation of the operation (fee, expire, type, body).

func (*Operation) Hash

func (o *Operation) Hash(chainId ChainId, pubKey ed25519.PublicKey) []byte

Hash returns the blake3 hash of the operation contents prefixed with the chain ID and public key, as required by the Massa signing scheme.

func (*Operation) ReadFrom

func (o *Operation) ReadFrom(r io.Reader) (int64, error)

ReadFrom reads an operation from the given reader.

func (*Operation) Sign

func (o *Operation) Sign(chainId ChainId, key crypto.Signer) ([]byte, error)

Sign signs the given operation and returns a serialized signed operation suitable for submission to the network. The key must be an Ed25519 signer.

See: https://docs.massa.net/docs/learn/operation-format-execution

func (*Operation) UnmarshalBinary

func (o *Operation) UnmarshalBinary(b []byte) error

UnmarshalBinary decodes an operation from its binary representation.

type OperationBody

type OperationBody interface {
	Bytes() []byte
	UnmarshalBinary(data []byte) error
	Type() OperationType
	ReadFrom(r io.Reader) (int64, error)
}

OperationBody is the interface implemented by all operation body types.

type OperationType

type OperationType uint32

OperationType identifies the kind of operation in the Massa network.

const (
	OpTransaction OperationType = iota // Transfer MAS coins
	OpRollBuy                          // Buy rolls for staking
	OpRollSell                         // Sell staking rolls
	OpExecuteSC                        // Execute smart contract bytecode
	OpCallSC                           // Call a smart contract function
)

Massa operation types.

type PublicKey

type PublicKey struct {
	Version uint64
	PubKey  ed25519.PublicKey
}

PublicKey represents a Massa Ed25519 public key with a version prefix.

func (*PublicKey) AsAddress

func (pk *PublicKey) AsAddress() *Address

AsAddress derives the user account Address from the public key by hashing the serialized key bytes with blake3.

func (*PublicKey) Bytes

func (pk *PublicKey) Bytes() []byte

Bytes returns the binary encoding of the public key (version varint followed by the raw Ed25519 key bytes).

func (*PublicKey) MarshalBinary

func (pk *PublicKey) MarshalBinary() ([]byte, error)

MarshalBinary encodes the public key in massa byte format (for compatibility).

func (*PublicKey) MarshalText

func (pk *PublicKey) MarshalText() (text []byte, err error)

MarshalText implements encoding.TextMarshaler.

func (*PublicKey) String

func (pk *PublicKey) String() string

String returns the Massa text representation of the public key (P prefix followed by base58check-encoded version and key bytes).

func (*PublicKey) UnmarshalText

func (pk *PublicKey) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler by parsing a Massa public key string (e.g. "P1t4JZwHhWNLt4xYabCbukyVNxSbhYPdF6wCYuRmDuHD784juxd").

type RPC

type RPC struct {
	// contains filtered or unexported fields
}

RPC wraps gRPC client connections to a Massa node, providing convenient methods for common operations.

func New

func New(target string, opts ...grpc.DialOption) (*RPC, error)

New returns a new RPC client connected to the given Massa node target (e.g. "localhost:33037").

func (*RPC) Close

func (rpc *RPC) Close() error

Close closes the underlying gRPC client connection.

func (*RPC) GetSlotTransfers

func (rpc *RPC) GetSlotTransfers(ctx context.Context, finality massagrpc.FinalityLevel) (chan *massagrpc.NewSlotTransfersResponse, io.Closer, error)

GetSlotTransfers opens a streaming connection that receives transfer events for each new slot. It requires the Massa node to be compiled with feature massa-node/execution-trace. The returned channel delivers responses until the stream ends or encounters an error. The caller must call Close on the returned io.Closer to release resources.

func (*RPC) GetStatus

func (rpc *RPC) GetStatus(ctx context.Context) (*massagrpc.PublicStatus, error)

GetStatus returns the status of the connected Massa node.

func (*RPC) Public

func (rpc *RPC) Public() massagrpc.PublicServiceClient

Public exposes the raw gRPC public service interface for advanced usage.

func (*RPC) SendOperations

func (rpc *RPC) SendOperations(ctx context.Context, op ...[]byte) ([]string, error)

SendOperations submits one or more signed operations to the Massa node and returns the resulting operation IDs.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL