neoutils

package
v0.0.0-...-cbe201a Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2019 License: MIT Imports: 33 Imported by: 6

README

NEO utilities

This package contains useful functions that make your life easier when working with NEO blockchain.

List of functions available in this library
Wallet
import "github.com/o3labs/neo-utils/neoutils"
Wallet struct
type Wallet struct {
	PublicKey       []byte
	PrivateKey      []byte
	Address         string
	WIF             string
	HashedSignature []byte
}

Create a new wallet address for NEO blockchain
neoutils.NewWallet() (*Wallet, error)
Restore a wallet from WIF
neoutils.GenerateFromWIF(wif string) (*Wallet, error)
Restore a wallet from raw private key string
neoutils.GenerateFromPrivateKey(privateKey string) (*Wallet, error)

Encryption
import "github.com/o3labs/neo-utils/neoutils"
Sign data using ECDSA
neoutils.Sign(data []byte, key string) ([]byte, error) 
Encrypt data using AES
neoutils.Encrypt(key []byte, text string) string 
Decrypt AES encrypted data
neoutils.Decrypt(key []byte, encryptedText string) string
Public key encryption using ECDH
(w *Wallet) ComputeSharedSecret(publicKey []byte) []byte
Create N-parts shared secret using Shamir's Secret Sharing
neoutils.GenerateShamirSharedSecret(secret string) (*SharedSecret, error)
Restore data from shared secret using Shamir's Secret Sharing
neoutils.RecoverFromSharedSecret(first []byte, second []byte) (string, error)
NEO Nodes utilities
import "github.com/o3labs/neo-utils/neoutils"
Select best node

Select NEO best node by measuring the latency between caller and the nodes concurrently.

type SeedNodeResponse struct {
	URL          string
	BlockCount   int
	ResponseTime int64 //milliseconds
}

neoutils.SelectBestSeedNode(commaSeparatedURLs string) *SeedNodeResponse 

Utilities methods
import "github.com/o3labs/neo-utils/neoutils"
Reverse bytes
neoutils.ReverseBytes(b []byte) []byte 
Hex string to bytes
neoutils.HexTobytes(hexstring string) (b []byte)
Bytes to hex string
neoutils.BytesToHex(b []byte) string
Convert script hash to NEO address
neoutils.ScriptHashToNEOAddress(scriptHash string) string
Convert NEO Address to script hash
neoutils.NEOAddressToScriptHash(neoAddress string) string 
Validate NEO Address
neoutils.ValidateNEOAddress(address string) bool 
Convert Byte array to big int
neoutils.ConvertByteArrayToBigInt(hexString string) *big.Int
Parse NEP9 URI
type SimplifiedNEP9 struct {
	To      string  `json:"to"`
	AssetID string  `json:"assetID"`
	Amount  float64 `json:"amount"`
}
neoutils.ParseNEP9URI(uri string) (*SimplifiedNEP9, error) 

NEO JSON RPC
import "github.com/o3labs/neo-utils/neoutils/neorpc"
Get contract state with smart contract's script hash
client := neorpc.NewClient("http://localhost:30333")
if client == nil {
	return
}

result := client.GetContractState("ce575ae1bb6153330d20c560acb434dc5755241b")
Send raw transaction
client := neorpc.NewClient("http://localhost:30333")
if client == nil {
	return
}
raw := ""
result := client.SendRawTransaction(raw)
Get raw transaction with TXID
client := neorpc.NewClient("http://localhost:30333")
if client == nil {
	return
}
txID := "bde02f8c6482e23d5b465259e3e438f0acacaba2a7a938d5eecd90bba0e9d1ad"
result := client.GetRawTransaction(txID)

City of Zion APIs
import "github.com/o3labs/neo-utils/neoutils/coz"
Get unspent data by NEO Address
client := coz.NewClient("http://127.0.0.1:5000")
unspent, err := client.GetUnspentByAddress("AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y")
for _, v := range unspent.GAS.Unspent {
	log.Printf("%+v", v)
}	

NEO Smart contract
import "github.com/o3labs/neo-utils/neoutils/smartcontract"
Generate invocation script data
smartcontract.GenerateContractInvocationData(scriptHash ScriptHash, operation string, args []interface{}) []byte
Generate invocation inputs data
smartconract.GenerateTransactionInput(unspent Unspent, assetToSend NativeAsset, amountToSend float64) ([]byte, error)
Generate invocation output data
smartcontract.GenerateTransactionOutput(sender NEOAddress, receiver NEOAddress, unspent Unspent, assetToSend NativeAsset, amountToSend float64) ([]byte, error)
Generate transaction attributes data
smartcontract.GenerateTransactionAttributes(attributes map[TransactionAttribute][]byte) ([]byte, error)
Generate invocation and verification script with signatures
smartcontract.GenerateVerificationScripts(signatures []TransactionSignature) []byte
Parse raw transaction's script to operation name and args
p := smartcontract.NewParserWithScript("51143acefb110cba488ae0d809f5837b0ac9c895405e52c10c6d696e74546f6b656e73546f67b17f078543788c588ce9e75544e325a050f8c1b7")

//you can define the known method signature here
type methodSignature struct {
	Operation smartcontract.Operation  //operation
	To        smartcontract.NEOAddress //args[0]
	Amount    int                      //args[1]
}
m := methodSignature{}
list, err := p.Parse(&m)
if err != nil {
	return
}
for _, v := range list {
	log.Printf("%+v", v.(*methodSignature))
}
Parse raw transaction's script that contains multiple appcall
script := `0500bca06501145a936d7abbaae28579dd36609f910f9b50de972f147bee835ff211327677c453d5f19b693e70a361ab53c1087472616e7366657267b6155db85e53298f01e0280cc2f21a0f40c4e808f10400e1f505147e548ecd2a87dd58731e6171752b1aa11494c62f147bee835ff211327677c453d5f19b693e70a361ab53c1087472616e7366657267b6155db85e53298f01e0280cc2f21a0f40c4e808f10500dc5c240214c10704464fade3197739536450ec9531a1f24a37147bee835ff211327677c453d5f19b693e70a361ab53c1087472616e7366657267b6155db85e53298f01e0280cc2f21a0f40c4e808f166b2263911344b5b15`
p := smartcontract.NewParserWithScript(script)
type methodSignature struct {
	Operation smartcontract.Operation  //operation
	From      smartcontract.NEOAddress //args[0]
	To        smartcontract.NEOAddress //args[1]
	Amount    int                      //args[2]
}
m := methodSignature{}
list, err := p.Parse(&m)
if err != nil {
	return
}

for _, v := range list {
	log.Printf("%+v", v.(*methodSignature))
}
Get invoked operations from raw transaction's script data
p := smartcontract.NewParserWithScript("51143acefb110cba488ae0d809f5837b0ac9c895405e52c10c6d696e74546f6b656e73546f67b17f078543788c588ce9e75544e325a050f8c1b7")
result, err := p.GetListOfOperations()
if err != nil {
	return
}

log.Printf("result = %v", result)
Get invoked smart contract script hashes from raw transaction's script data
p := smartcontract.NewParserWithScript("51143acefb110cba488ae0d809f5837b0ac9c895405e52c10c6d696e74546f6b656e73546f67b17f078543788c588ce9e75544e325a050f8c1b7")
result, err := p.GetListOfScriptHashes()
if err != nil {
	return
}

log.Printf("result = %v", result)
Generate ready-for-sendrawtransaction smart contract invocation data
var validSmartContract = neoutils.UseSmartContract("b7c1f850a025e34455e7e98c588c784385077fb1")
validSmartContract.GenerateInvokeFunctionRawTransaction(wallet Wallet, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte, operation string, args []interface{}) ([]byte, error)

Documentation

Overview

WARNING: not finish

Index

Constants

View Source
const (
	VERSION = "1.3.0"
)

Variables

This section is empty.

Functions

func BuildOntologyInvocationTransaction

func BuildOntologyInvocationTransaction(contract string, method string, args string, gasPrice int, gasLimit int, wif string, payer string) (string, error)

func BytesToHex

func BytesToHex(b []byte) string

Simple bytes to Hex

func ClaimONG

func ClaimONG(endpoint string, gasPrice int, gasLimit int, wif string) (string, error)

func ConvertByteArrayToBigInt

func ConvertByteArrayToBigInt(hexString string) *big.Int

Convert byte array to big int

func Decrypt

func Decrypt(key []byte, encryptedText string) string

Decrypt AES encrypted string in base64 format to decrypted string

func DeploySmartContractScript

func DeploySmartContractScript(contractInfo SmartContractInfo, wallet Wallet, asset smartcontract.NativeAsset, amount float64, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte) ([]byte, error)

func Encrypt

func Encrypt(key []byte, text string) string

Encrypt string to base64 format using AES

func GenerateNEP6FromEncryptedKey

func GenerateNEP6FromEncryptedKey(walletName, addressLabel, address, encryptedKey string) string

func GetVarUInt

func GetVarUInt(value int64) []byte

func Hash160

func Hash160(data []byte) []byte

func Hash256

func Hash256(b []byte) []byte

func HexTobytes

func HexTobytes(hexstring string) (b []byte)

Simple hex string to bytes

func NEOAddressToScriptHashWithEndian

func NEOAddressToScriptHashWithEndian(neoAddress string, endian binary.ByteOrder) string

Convert NEO address to script hash

func NEOAddresstoScriptHashBigEndian

func NEOAddresstoScriptHashBigEndian(neoAddress string) string

func NEP2Decrypt

func NEP2Decrypt(key, passphrase string) (s string, err error)

func NeonJSTXSerializer

func NeonJSTXSerializer(tx NeonJSTransaction) []byte

func OEP4Transfer

func OEP4Transfer(endpoint string, contract string, fromAddress string, toAddress string, amount float64, tokenDecimals int, gasPrice int, gasLimit int, wif string) (string, error)

OEP4Transfer : Transfer OEP4 token

func ONTAddressFromPublicKey

func ONTAddressFromPublicKey(publicKey []byte) string

func OntologyBuildGetDDO

func OntologyBuildGetDDO(ontid string) (string, error)

func OntologyGetBlockCount

func OntologyGetBlockCount(endpoint string) (int, error)

func OntologyGetBlockWithHash

func OntologyGetBlockWithHash(endpoint string, blockHash string) (string, error)

func OntologyGetBlockWithHeight

func OntologyGetBlockWithHeight(endpoint string, blockHeight int) (string, error)

func OntologyGetRawTransaction

func OntologyGetRawTransaction(endpoint string, txID string) (string, error)

func OntologyGetStorage

func OntologyGetStorage(endpoint string, scriptHash string, key string) (string, error)

func OntologyGetUnboundONG

func OntologyGetUnboundONG(endpoint string, address string) (string, error)

func OntologyInvoke

func OntologyInvoke(endpoint string, contract string, method string, args string, gasPrice int, gasLimit int, wif string, payer string) (string, error)

OntologyInvoke : Invoke a neovm contract in Ontology

func OntologyMakeRegister

func OntologyMakeRegister(gasPrice int, gasLimit int, ontidWif string, payerWif string) (string, error)

func OntologySendPreExecRawTransaction

func OntologySendPreExecRawTransaction(endpoint string, raw string) (string, error)

func OntologySendRawTransaction

func OntologySendRawTransaction(endpoint string, raw string) (string, error)

func OntologyTransfer

func OntologyTransfer(endpoint string, gasPrice int, gasLimit int, wif string, asset string, to string, amount float64) (string, error)

func PublicKeyToNEOAddress

func PublicKeyToNEOAddress(publicKeyBytes []byte) string

func RecoverFromSharedSecret

func RecoverFromSharedSecret(first []byte, second []byte) (string, error)

Recover the secret from shared secrets.

func ReverseBytes

func ReverseBytes(b []byte) []byte

func ScriptHashToNEOAddress

func ScriptHashToNEOAddress(scriptHash string) string

Convert script hash to NEO address This method takes Big Endian Script hash

func SerializeTX

func SerializeTX(jsonString string) []byte

func Sign

func Sign(data []byte, key string) ([]byte, error)

Sign data using ECDSA with a private key

func VMCodeToNEOAddress

func VMCodeToNEOAddress(vmCode []byte) string

func ValidateNEOAddress

func ValidateNEOAddress(address string) bool

Validate NEO address

func Verify

func Verify(publicKey []byte, signature []byte, hash []byte) bool

Verify signed hash using public key

func WriteVarUint

func WriteVarUint(w io.Writer, val uint64) error

Types

type BlockCountResponse

type BlockCountResponse struct {
	Jsonrpc      string `json:"jsonrpc"`
	ID           int    `json:"id"`
	Result       int    `json:"result"`
	ResponseTime int64  `json:"-"`
}

type FetchSeedRequest

type FetchSeedRequest struct {
	Response *BlockCountResponse
	URL      string
}

type MultiSig

type MultiSig struct {
	NumberOfRequiredSignatures int
	PublicKeys                 [][]byte
}

func (*MultiSig) CreateMultiSigRedeemScript

func (m *MultiSig) CreateMultiSigRedeemScript() ([]byte, error)

type MultiSigInterface

type MultiSigInterface interface {
	CreateMultiSigRedeemScript() ([]byte, error)
}

type NEP2

type NEP2 struct {
	EncryptedKey string
	Address      string
}

func NEP2Encrypt

func NEP2Encrypt(wif string, passphrase string) (*NEP2, error)

type NEP5

type NEP5 struct {
	ScriptHash       smartcontract.ScriptHash
	NetworkFeeAmount smartcontract.NetworkFeeAmount //allow users to override the network fee here
}

func UseNEP5WithNetworkFee

func UseNEP5WithNetworkFee(scriptHashHex string, networkFeeAmount smartcontract.NetworkFeeAmount) *NEP5

func (*NEP5) MintTokensRawTransaction

func (n *NEP5) MintTokensRawTransaction(wallet Wallet, assetToSend smartcontract.NativeAsset, amount float64, unspent smartcontract.Unspent, remark string) ([]byte, string, error)

func (*NEP5) TransferNEP5RawTransaction

func (n *NEP5) TransferNEP5RawTransaction(wallet Wallet, toAddress smartcontract.NEOAddress, amount float64, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte) ([]byte, string, error)

type NEP5Interface

type NEP5Interface interface {
	MintTokensRawTransaction(wallet Wallet, assetToSend smartcontract.NativeAsset, amount float64, unspent smartcontract.Unspent, remark string) ([]byte, string, error)
	TransferNEP5RawTransaction(wallet Wallet, toAddress smartcontract.NEOAddress, amount float64, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte) ([]byte, string, error)
}

type NativeAsset

type NativeAsset struct {
	NetworkFeeAmount smartcontract.NetworkFeeAmount //allow users to override the network fee here
}

func UseNativeAsset

func UseNativeAsset(networkFeeAmount smartcontract.NetworkFeeAmount) NativeAsset

func (*NativeAsset) GenerateRawTx

func (n *NativeAsset) GenerateRawTx(fromAddress string, asset smartcontract.NativeAsset, amount float64, to smartcontract.NEOAddress, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte) ([]byte, string, error)

func (*NativeAsset) SendNativeAssetRawTransaction

func (n *NativeAsset) SendNativeAssetRawTransaction(wallet Wallet, asset smartcontract.NativeAsset, amount float64, to smartcontract.NEOAddress, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte) ([]byte, string, error)

type NativeAssetInterface

type NativeAssetInterface interface {
	SendNativeAssetRawTransaction(wallet Wallet, asset smartcontract.NativeAsset, amount float64, to smartcontract.NEOAddress, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte) ([]byte, string, error)
	GenerateRawTx(fromAddress string, asset smartcontract.NativeAsset, amount float64, to smartcontract.NEOAddress, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte) ([]byte, string, error)
}

type NeonJSTransaction

type NeonJSTransaction struct {
	Sha256 string `json:"sha256"`
	Hash   string `json:"hash"`
	Inputs []struct {
		PrevIndex int    `json:"prevIndex"`
		PrevHash  string `json:"prevHash"`
	} `json:"inputs"`
	Outputs []struct {
		AssetID    string      `json:"assetId"`
		ScriptHash string      `json:"scriptHash"`
		Value      interface{} `json:"value"`
	} `json:"outputs"`
	Script     string `json:"script"`
	Version    int    `json:"version"`
	Type       int    `json:"type"`
	Attributes []struct {
		Usage int    `json:"usage"`
		Data  string `json:"data"`
	} `json:"attributes"`
	Scripts []interface{} `json:"scripts"`
	Gas     int           `json:"gas"`
}

type NodeList

type NodeList struct {
	URL []string
}

type ONTAccount

type ONTAccount struct {
	Address    string //base58
	WIF        string
	PrivateKey []byte
	PublicKey  []byte
}

func ONTAccountFromPrivateKey

func ONTAccountFromPrivateKey(privateKeyBytes []byte) *ONTAccount

func ONTAccountFromWIF

func ONTAccountFromWIF(wif string) *ONTAccount

func ONTCreateAccount

func ONTCreateAccount() *ONTAccount

type OntologyBalances

type OntologyBalances struct {
	Ont string
	Ong string
}

func OntologyGetBalance

func OntologyGetBalance(endpoint string, address string) (*OntologyBalances, error)

type RawTransaction

type RawTransaction struct {
	TXID string
	Data []byte
}

func MintTokensRawTransactionMobile

func MintTokensRawTransactionMobile(network string, scriptHash string, wif string, sendingAssetID string, amount float64, remark string, networkFeeAmountInGAS float64) (*RawTransaction, error)

type SeedNodeResponse

type SeedNodeResponse struct {
	URL          string
	BlockCount   int
	ResponseTime int64 //milliseconds
}

func SelectBestSeedNode

func SelectBestSeedNode(commaSeparatedURLs string) *SeedNodeResponse

type SharedSecret

type SharedSecret struct {
	First  []byte
	Second []byte
}

Shared Secret with 2 parts.

func GenerateShamirSharedSecret

func GenerateShamirSharedSecret(secret string) (*SharedSecret, error)

Generate Shamir shared secret to SharedSecret struct.

type SimplifiedNEP9

type SimplifiedNEP9 struct {
	To     string  `json:"to"`
	Asset  string  `json:"assetID"`
	Amount float64 `json:"amount"`
}

func ParseNEP9URI

func ParseNEP9URI(uri string) (*SimplifiedNEP9, error)

type SmartCodeEvent

type SmartCodeEvent struct {
	TxHash      string
	State       int
	GasConsumed int
}

func OntologyGetSmartCodeEvent

func OntologyGetSmartCodeEvent(endpoint string, txHash string) (*SmartCodeEvent, error)

type SmartContract

type SmartContract struct {
	ScriptHash       smartcontract.ScriptHash
	NetworkFeeAmount smartcontract.NetworkFeeAmount //allow users to override the network fee here
}

func (*SmartContract) GenerateInvokeFunctionRawTransaction

func (s *SmartContract) GenerateInvokeFunctionRawTransaction(wallet Wallet, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte, operation string, args []interface{}) ([]byte, error)

func (*SmartContract) GenerateInvokeFunctionRawTransactionWithAmountToSend

func (s *SmartContract) GenerateInvokeFunctionRawTransactionWithAmountToSend(wallet Wallet, asset smartcontract.NativeAsset, amount float64, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte, operation string, args []interface{}) ([]byte, error)

type SmartContractInfo

type SmartContractInfo struct {
	AVMHEX      string
	Name        string
	Version     string
	Author      string
	Email       string
	Description string
	Properties  smartcontract.Properties
	InputTypes  []smartcontract.ParameterType
	ReturnType  smartcontract.ParameterType
}

func (*SmartContractInfo) GetScriptHash

func (s *SmartContractInfo) GetScriptHash() string

func (*SmartContractInfo) Serialize

func (s *SmartContractInfo) Serialize() []byte

type SmartContractInterface

type SmartContractInterface interface {
	//NOTE: these two methods are actually pretty similar in implementation.
	//the only difference is GenerateInvokeFunctionRawTransactionWithAmountToSend is used to send NEO/GAS to SmartContract
	//however, I want to keep them separated
	GenerateInvokeFunctionRawTransaction(wallet Wallet, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte, operation string, args []interface{}) ([]byte, error)
	GenerateInvokeFunctionRawTransactionWithAmountToSend(wallet Wallet, asset smartcontract.NativeAsset, amount float64, unspent smartcontract.Unspent, attributes map[smartcontract.TransactionAttribute][]byte, operation string, args []interface{}) ([]byte, error)
}

func UseSmartContract

func UseSmartContract(scriptHashHex string) SmartContractInterface

func UseSmartContractWithNetworkFee

func UseSmartContractWithNetworkFee(scriptHashHex string, feeAmount smartcontract.NetworkFeeAmount) SmartContractInterface

type Wallet

type Wallet struct {
	PublicKey       []byte
	PrivateKey      []byte
	Address         string
	WIF             string
	HashedSignature []byte
}

func GenerateFromPrivateKey

func GenerateFromPrivateKey(privateKey string) (*Wallet, error)

Generate a wallet from a private key

func GenerateFromWIF

func GenerateFromWIF(wif string) (*Wallet, error)

Generate a wallet from a WIF

func NEP2DecryptToWallet

func NEP2DecryptToWallet(key, passphrase string) (*Wallet, error)

func NewWallet

func NewWallet() (*Wallet, error)

Create a new wallet.

func (*Wallet) ComputeSharedSecret

func (w *Wallet) ComputeSharedSecret(publicKey []byte) []byte

Compute shared secret using ECDH

Directories

Path Synopsis
https://github.com/CityOfZion/neo-go/ https://github.com/CityOfZion/neo-go/
https://github.com/CityOfZion/neo-go/ https://github.com/CityOfZion/neo-go/
Package rfc6979 is an implementation of RFC 6979's deterministic DSA.
Package rfc6979 is an implementation of RFC 6979's deterministic DSA.
Package sss implements Shamir's Secret Sharing algorithm over GF(2^8).
Package sss implements Shamir's Secret Sharing algorithm over GF(2^8).

Jump to

Keyboard shortcuts

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