Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ICON Network Support #34

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified .DS_Store
Binary file not shown.
4 changes: 2 additions & 2 deletions chain/filecoin/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package filecoin
import (
"bytes"
"fmt"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"

filaddress "github.com/filecoin-project/go-address"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/specs-actors/actors/abi"
"github.com/filecoin-project/specs-actors/actors/abi/big"
"github.com/minio/blake2b-simd"
"github.com/renproject/multichain/api/account"
"github.com/renproject/multichain/api/address"
Expand Down
2 changes: 1 addition & 1 deletion chain/filecoin/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import (
"net/http"

"github.com/filecoin-project/go-jsonrpc"
"github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/lotus/api"
filclient "github.com/filecoin-project/lotus/api/client"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/specs-actors/actors/crypto"
"github.com/ipfs/go-cid"
"github.com/renproject/multichain/api/account"
"github.com/renproject/pack"
Expand Down
137 changes: 137 additions & 0 deletions chain/icon/account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package icon

import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/icon-project/goloop/server/jsonrpc"
"github.com/renproject/multichain/api/account"
"github.com/renproject/multichain/api/address"
"github.com/renproject/multichain/api/contract"
"github.com/renproject/multichain/chain/icon/crypto"
"github.com/renproject/multichain/chain/icon/intconv"
"github.com/renproject/multichain/chain/icon/transaction"
"github.com/renproject/pack"
"strconv"
"time"
)

type RawMessage []byte

// Tx ...
type Tx struct {
Version jsonrpc.HexInt `json:"version" validate:"required,t_int"`
FromAddress address.Address `json:"from" validate:"required,t_addr_eoa"`
ToAddress address.Address `json:"to" validate:"required,t_addr"`
Amount jsonrpc.HexInt `json:"value,omitempty" validate:"optional,t_int"`
StepLimit jsonrpc.HexInt `json:"stepLimit" validate:"required,t_int"`
Timestamp jsonrpc.HexInt `json:"timestamp" validate:"required,t_int"`
NID jsonrpc.HexInt `json:"nid" validate:"required,t_int"`
Salt jsonrpc.HexInt `json:"nonce,omitempty" validate:"optional,t_int"`
Signature string `json:"signature" validate:"required,t_sig"`
DataType *string `json:"dataType,omitempty" validate:"optional,call|deploy|message"`
Data RawMessage `json:"data,omitempty"`
}

// PrivateKey is a type representing a private key.
// for both private key and public key
type PrivateKey pack.Bytes

// Hash ...
func (tx *Tx) Hash() pack.Bytes {
h, err := tx.Sighashes()
if err != nil {
return pack.Bytes{}
} else {
b := h[0][:]
return pack.NewBytes(b)
}
}

// To ...
func (tx *Tx) To() address.Address {
return tx.ToAddress
}

// From ...
func (tx *Tx) From() address.Address {
return tx.FromAddress
}

// Value ...
func (tx *Tx) Value() pack.U256 {
output, _ := strconv.ParseInt(string(tx.Amount)[2:], 16, 64)
return pack.NewU256FromU64(pack.NewU64(uint64(output)))
}

// Nonce ...
func (tx *Tx) Nonce() pack.U256 {
output, _ := strconv.ParseInt(string(tx.Salt)[2:], 16, 64)
return pack.NewU256FromU64(pack.NewU64(uint64(output)))
}

// Serialize ...
func (tx *Tx) Serialize() (pack.Bytes, error) {
txSerializeExcludes := map[string]bool{"signature": true}
//tx.Timestamp = jsonrpc.HexInt(intconv.FormatInt(time.Now().UnixNano() / int64(time.Microsecond)))
js, err := json.Marshal(tx)
if err != nil {
return nil, err
}
return transaction.SerializeJSON(js, nil, txSerializeExcludes)
}

// Sighashes returns the digests that must be signed before the transaction
// can be submitted by the client.
func (tx *Tx) Sighashes() ([]pack.Bytes32, error) {
bs, _ := tx.Serialize()
bs = append([]byte("icx_sendTransaction."), bs...)
sighashes := make([]pack.Bytes32, 1)
d := crypto.SHA3Sum256(bs)
sighash := [32]byte{}
copy(sighash[:], d)
sighashes[0] = pack.NewBytes32(sighash)
return sighashes, nil
}

// Payload returns the memo attached to the transaction.
func (tx *Tx) Payload() contract.CallData {
return contract.CallData(pack.Bytes(make([]byte, 0)))
}
func (tx *Tx) Sign(signatures []pack.Bytes65, pubKey pack.Bytes) error {
if len(signatures) != 1 {
return fmt.Errorf("expected 1 signature, got %v signatures", len(signatures))
}
tx.Signature = base64.StdEncoding.EncodeToString(signatures[0].Bytes())
return nil
}

// TxBuilder represents a transaction builder that builds transactions to be
// broadcasted to the icon network. The TxBuilder is configured using a
// gas price and gas limit.
type TxBuilder struct {
chainID string
}

// NewTxBuilder creates a new transaction builder.
func NewTxBuilder(chainId string) TxBuilder {
return TxBuilder{chainID: chainId}
}

// BuildTx ...
func (txBuilder TxBuilder) BuildTx(from, to address.Address, value pack.U256, nonce pack.U256, stepLimit pack.U256, gasPrice pack.U256, payload pack.Bytes) (account.Tx, error) {

stepHex := fmt.Sprintf("0x%x", stepLimit.Int())
valueHex := fmt.Sprintf("0x%x", value.Int())
tx := Tx{
Version: "0x3",
FromAddress: from,
ToAddress: to,
StepLimit: jsonrpc.HexInt(stepHex),
Amount: jsonrpc.HexInt(valueHex),
Timestamp: jsonrpc.HexInt(intconv.FormatInt(time.Now().UnixNano() / int64(time.Microsecond))),
NID: jsonrpc.HexInt(txBuilder.chainID),
Salt: "0x1",
}
return &tx, nil
}
136 changes: 136 additions & 0 deletions chain/icon/address.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package icon

import (
"encoding/hex"
"log"

"github.com/renproject/multichain/api/address"
"github.com/renproject/multichain/chain/icon/crypto"
"github.com/renproject/pack"
)

// An Address is a public address that can be encoded/decoded to/from strings.
// Addresses are usually formatted different between different network
// configurations.
type Address [AddressBytes]byte

const (
// AddressIDBytes represents an Icon address body size
AddressIDBytes = 20
// AddressBytes represents an Icon address byte size
AddressBytes = AddressIDBytes + 1
)

// AddressEncodeDecoder encapsulates fields that implement the
// address.EncodeDecoder interface
type AddressEncodeDecoder struct {
AddressEncoder
AddressDecoder
}

// AddressEncoder implements the address.Encoder interface
type AddressEncoder struct{}

// AddressDecoder implements the address.Decoder interface
type AddressDecoder struct{}

// NewAddressEncodeDecoder constructs a new EncodeDecoder.
func NewAddressEncodeDecoder() address.EncodeDecoder {
return AddressEncodeDecoder{
AddressEncoder: NewAddressEncoder(),
AddressDecoder: NewAddressDecoder(),
}
}

// NewAddressDecoder constructs a new AddressDecoder.
func NewAddressDecoder() AddressDecoder {
return AddressDecoder{}
}

// NewAddressEncoder constructs a new AddressEncoder.
func NewAddressEncoder() AddressEncoder {
return AddressEncoder{}
}

// EncodeAddress consumes raw bytes and encodes them to a human-readable
// address format.
func (ae AddressEncoder) EncodeAddress(raw address.RawAddress) (address.Address, error) {
post := hex.EncodeToString(raw[1:])
if raw[0] == 1 {
return address.Address("cx" + post), nil
}
return address.Address("hx" + post), nil
}

// DecodeAddress consumes a human-readable representation of an icon
// compatible address and decodes it to its raw bytes representation.
func (de AddressDecoder) DecodeAddress(ai address.Address) (address.RawAddress, error) {
var isContract = false
if len(ai) >= 2 {
switch {
case ai[0:2] == "cx":
isContract = true
ai = ai[2:]
case ai[0:2] == "hx":
ai = ai[2:]
case ai[0:2] == "0x":
ai = ai[2:]
}
}
a, err := hex.DecodeString(string(ai))
if err != nil {
return a, err
}
res := make(address.RawAddress, len(a)+1)
copy(res[1:], a)
if isContract {
res[0] = 1
} else {
res[0] = 0
}
return address.RawAddress(pack.Bytes(res)), nil
}

// NewAccountAddressFromPublicKey generates an address from a public key
func NewAccountAddressFromPublicKey(pubKey *crypto.PublicKey) *Address {
a := new(Address)
pk := pubKey.SerializeUncompressed()
if pk == nil {
log.Panicln("FAIL invalid public key:", pubKey)
}
digest := crypto.SHA3Sum256(pk[1:])
a.SetTypeAndID(false, digest[len(digest)-20:])
return a
}

// SetTypeAndID generates an address from a public key
func (a *Address) SetTypeAndID(ic bool, id []byte) error {
if id == nil {
return nil
}
switch {
case len(id) < AddressIDBytes:
copy(a[AddressIDBytes-len(id)+1:], id)
default:
copy(a[1:], id)
}
if ic {
a[0] = 1
} else {
a[0] = 0
}
return nil
}

// String returns the address as a human-readable hex string.
func (a *Address) String() string {
if a[0] == 1 {
return "cx" + hex.EncodeToString(a[1:])
}
return "hx" + hex.EncodeToString(a[1:])
}

// Bytes returns the address as a slice of 20 bytes.
func (a *Address) Bytes() []byte {
return (*a)[:]
}
94 changes: 94 additions & 0 deletions chain/icon/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package icon

import (
"bytes"
"context"
"encoding/json"
"github.com/icon-project/goloop/client"
v3 "github.com/icon-project/goloop/server/v3"
"github.com/renproject/multichain/api/account"
"github.com/renproject/multichain/api/address"
"log"
"net/http"
"time"

"github.com/icon-project/goloop/server/jsonrpc"
"github.com/renproject/pack"
)

const jsonprcVersion = "2.0"

// Request ...
type Request struct {
Version string `json:"jsonrpc" validate:"required,version"`
Method string `json:"method" validate:"required"`
Params json.RawMessage `json:"params,omitempty"`
ID interface{} `json:"id"`
}

// Response ...
type Response struct {
Version string `json:"jsonrpc" validate:"required,version"`
ID interface{} `json:"id"`
Result Tx `json:"result"`
}

// Client ...
type Client struct {
v3 client.ClientV3
endpoint string
}

// NewClient returns a new Client.
func NewClient(endpoint pack.String) *Client {

return &Client{
v3: *client.NewClientV3(endpoint.String()),
endpoint: endpoint.String(),
}
}

// Tx ...
func (ct *Client) Tx(ctx context.Context, txHash pack.Bytes) (account.Tx, pack.U64, error) {
txResult, err := ct.v3.GetTransactionByHash(&v3.TransactionHashParam{Hash: jsonrpc.HexBytes(txHash)})
if err != nil {
return nil, pack.NewU64(0), err
}
return &Tx{
Version: txResult.Version,
Amount: txResult.Value,
FromAddress: address.Address(txResult.From.Address().String()),
ToAddress: address.Address(txResult.To.Address().String()),
StepLimit: txResult.StepLimit,
Signature: string(txResult.Signature.Bytes()),
Timestamp: txResult.TimeStamp,
NID: txResult.NID,
DataType: &txResult.DataType,
}, pack.NewU64(1), nil
}

// SubmitTx ...
func (ct *Client) SubmitTx(ctx context.Context, tx account.Tx) error {
_, err := ct.sendTransaction(tx)
return err
}

func (ct Client) sendTransaction(tx account.Tx) (*http.Response, error) {
rq := &Request{
Version: jsonprcVersion,
Method: "icx_sendTransaction",
ID: time.Now().UnixNano() / int64(time.Millisecond),
}
b, _ := json.Marshal(tx)
rq.Params = json.RawMessage(b)
reqB, err := json.Marshal(rq)
if err != nil {
return nil, err
}
res, err := http.Post(ct.endpoint, "application/json; charset=utf-8", bytes.NewReader(reqB))
if err != nil {
log.Panic(err)
return nil, err
}
return res, nil
}
Loading