Commit bff64a1c authored by suyanlong's avatar suyanlong

Add pkg

parent bef1229d
This diff is collapsed.
package client
import (
"math/rand"
"testing"
"time"
"gitlab.33.cn/link33/chain33-sdk-go/dapp/broker"
//"gitlab.33.cn/link33/chain33-sdk-go/dapp/broker"
)
var GenesisPriv = "cc38546e9e659d15e6b4893f0ab32a06d103931a8230b0bde71459d2b27d6944"
func Test_InitBroker(t *testing.T) {
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
resp, err := client.InitBroker("bxhv1", "chain33", GenesisPriv)
if err != nil {
t.Error(err)
}
t.Log(resp.Message)
}
func Test_EmitDataSwapInterchainEvent(t *testing.T) {
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
// 第一次存储
resp, err := client.KVStore("greet", "hello", GenesisPriv)
if err != nil {
t.Error(err)
}
time.Sleep(time.Second)
resp, err = client.EmitDataSwapInterchainEvent("mychannel&data_swapper", "greet", "greet", "", GenesisPriv)
if err != nil {
t.Error(err)
}
t.Log(resp.Data)
}
func Test_InterChainGet(t *testing.T) {
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
resp, err := client.InterChainGet("test")
if err != nil {
t.Error(err)
}
t.Log(string(resp.Data))
}
func Test_QueryBrokerInfo(t *testing.T) {
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
info, err := client.QueryBrokerInfo()
if err != nil {
t.Error(err)
}
t.Logf("appid:%s,version:%s", info.GetAppChainId(), info.GetBxhId())
meta, err := client.QueryOutterMeta()
if err != nil {
t.Error(err)
}
t.Log(meta.Meta)
}
func Test_PollEvent(t *testing.T) {
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
registerCh, eventCh, errCh := client.RegisterTxEvent(0, "broker", "EmitInterchainEvent")
t.Log("111111111111111")
ticker := time.Tick(5 * time.Second)
select {
case event := <-eventCh:
t.Log(event)
case err := <-errCh:
t.Error(err)
case <-ticker:
registerCh <- struct{}{}
return
}
registerCh <- struct{}{}
}
func Test_UpdateIndex(t *testing.T) {
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
event, err := client.QueryOutMessage("bxhv1:chain33:local&broker-fabric&broker", 1)
if err != nil {
t.Error(err)
}
tx := broker.UpdateIndex("", event.SrcServiceID, event.GetDstServiceID(), event.GetIndex(), 0, 1)
resp, err := client.SendTransactionSync(GenesisPriv, tx)
if err != nil {
t.Error(err)
}
t.Log(resp.Message)
}
func Test_QueryMeta(t *testing.T) {
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
resp, err := client.QueryOutMessage("bxhv1:chain33:local&broker-fabric&broker", 1)
if err != nil {
t.Error(err)
}
t.Log(resp)
respon, err := client.QueryInMessage("bxhv1:chain33:local&broker-fabric&broker", 1)
if err != nil {
t.Error(err)
}
t.Logf("status:%d", respon.Status)
meta, err := client.QueryOutterMeta()
if err != nil {
t.Error(err)
}
t.Log(meta.Meta)
}
func Test_Channel(t *testing.T) {
ch := make(chan int, 10)
ch <- 1
select {
case a := <-ch:
t.Log(a)
}
a := rand.Intn(2)
t.Log(a)
}
package client
import (
"encoding/json"
"fmt"
"strconv"
. "github.com/bitly/go-simplejson"
"gitlab.33.cn/link33/chain33-sdk-go/dapp/storage"
"gitlab.33.cn/link33/chain33-sdk-go/types"
)
// 回调解析函数
func ParseStorage(raw json.RawMessage) (interface{}, error) {
js, err := NewJson(raw)
if err != nil {
return nil, err
}
if contentStorge, ok := js.CheckGet("contentStorage"); ok {
contentHex, _ := contentStorge.Get("content").String()
content, _ := types.FromHex(contentHex)
key, _ := contentStorge.Get("key").String()
value, _ := contentStorge.Get("value").String()
op, _ := contentStorge.Get("op").Int()
storage := &types.Storage{Ty: storage.TyContentStorageAction, Value: &types.Storage_ContentStorage{ContentStorage: &types.ContentOnlyNotaryStorage{
Content: content,
Key: key,
Op: int32(op),
Value: value,
XXX_NoUnkeyedLiteral: struct{}{},
XXX_unrecognized: nil,
XXX_sizecache: 0,
}}}
return storage, nil
}
if linkStorge, ok := js.CheckGet("linkStorage"); ok {
linkHex, _ := linkStorge.Get("link").String()
link, _ := types.FromHex(linkHex)
key, _ := linkStorge.Get("key").String()
value, _ := linkStorge.Get("value").String()
storage := &types.Storage{Ty: storage.TyLinkStorageAction, Value: &types.Storage_LinkStorage{LinkStorage: &types.LinkNotaryStorage{
Link: link,
Key: key,
Value: value,
XXX_NoUnkeyedLiteral: struct{}{},
XXX_unrecognized: nil,
XXX_sizecache: 0,
}}}
return storage, nil
}
if hashStorge, ok := js.CheckGet("hashStorage"); ok {
hashHex, _ := hashStorge.Get("hash").String()
hash, _ := types.FromHex(hashHex)
key, _ := hashStorge.Get("key").String()
value, _ := hashStorge.Get("value").String()
storage := &types.Storage{Ty: storage.TyHashStorageAction, Value: &types.Storage_HashStorage{HashStorage: &types.HashOnlyNotaryStorage{
Hash: hash,
Key: key,
Value: value,
XXX_NoUnkeyedLiteral: struct{}{},
XXX_unrecognized: nil,
XXX_sizecache: 0,
}}}
return storage, nil
}
if encryptStorage, ok := js.CheckGet("encryptStorage"); ok {
contentHashHex, _ := encryptStorage.Get("contentHash").String()
contentHash, _ := types.FromHex(contentHashHex)
encryptContentHex, _ := encryptStorage.Get("encryptContent").String()
encryptContent, _ := types.FromHex(encryptContentHex)
nonceHex, _ := encryptStorage.Get("nonce").String()
nonce, _ := types.FromHex(nonceHex)
key, _ := encryptStorage.Get("key").String()
value, _ := encryptStorage.Get("value").String()
storage := &types.Storage{Ty: storage.TyEncryptStorageAction, Value: &types.Storage_EncryptStorage{EncryptStorage: &types.EncryptNotaryStorage{
EncryptContent: encryptContent,
ContentHash: contentHash,
Nonce: nonce,
Key: key,
Value: value,
XXX_NoUnkeyedLiteral: struct{}{},
XXX_unrecognized: nil,
XXX_sizecache: 0,
}}}
return storage, nil
}
if encryptStorage, ok := js.CheckGet("encryptShareStorage"); ok {
contentHashHex, _ := encryptStorage.Get("contentHash").String()
contentHash, _ := types.FromHex(contentHashHex)
encryptContentHex, _ := encryptStorage.Get("encryptContent").String()
encryptContent, _ := types.FromHex(encryptContentHex)
pubKeyHex, _ := encryptStorage.Get("pubKey").String()
pubKey, _ := types.FromHex(pubKeyHex)
key, _ := encryptStorage.Get("key").String()
value, _ := encryptStorage.Get("value").String()
storage := &types.Storage{Ty: storage.TyEncryptShareStorageAction, Value: &types.Storage_EncryptShareStorage{EncryptShareStorage: &types.EncryptShareNotaryStorage{
EncryptContent: encryptContent,
ContentHash: contentHash,
PubKey: pubKey,
Key: key,
Value: value,
XXX_NoUnkeyedLiteral: struct{}{},
XXX_unrecognized: nil,
XXX_sizecache: 0,
}}}
return storage, nil
}
return nil, fmt.Errorf("unknow type!")
}
// FIXME 解析跨链事件,系统json序列化有问题,非string字段全部转化为string字段了
func ParseInterChainEvent(raw json.RawMessage) (interface{}, error) {
js, err := NewJson(raw)
if err != nil {
return nil, err
}
index, err := strconv.ParseUint(js.Get("index").MustString(), 10, 64)
if err != nil {
return nil, err
}
ty, err := strconv.ParseUint(js.Get("type").MustString(), 10, 64)
if err != nil {
return nil, err
}
event := &types.InterchainEvent{
Index: index,
DstServiceID: js.Get("dstServiceID").MustString(),
SrcServiceID: js.Get("srcServiceID").MustString(),
Type: ty,
Func: js.Get("func").MustString(),
Args: js.Get("args").MustString(),
Argsrb: js.Get("argsrb").MustString(),
Argscb: js.Get("argscb").MustString(),
}
return event, nil
}
func ParseMeta(raw json.RawMessage) (interface{}, error) {
js, err := NewJson(raw)
if err != nil {
return nil, err
}
m := js.Get("meta").MustMap()
mk := make(map[string]uint64)
for k, v := range m {
value, _ := strconv.ParseUint(v.(string), 10, 64)
mk[k] = value
}
// 移除broker键值
delete(mk, "broker")
return &types.Meta{Meta: mk}, nil
}
...@@ -11,9 +11,11 @@ import ( ...@@ -11,9 +11,11 @@ import (
"net/http" "net/http"
"strings" "strings"
sdk "gitlab.33.cn/link33/chain33-sdk-go" "gitlab.33.cn/link33/sidecar-client-chain33/util"
"gitlab.33.cn/link33/chain33-sdk-go/crypto"
"gitlab.33.cn/link33/chain33-sdk-go/types" types33 "github.com/33cn/chain33/types"
"gitlab.33.cn/link33/sidecar-client-chain33/crypto"
"go.starlark.net/lib/proto" "go.starlark.net/lib/proto"
) )
...@@ -184,14 +186,14 @@ func (client *Client) SendTransaction(signedTx string) (string, error) { ...@@ -184,14 +186,14 @@ func (client *Client) SendTransaction(signedTx string) (string, error) {
return res, nil return res, nil
} }
func (client *Client) SendTransactionSync(privkey string, tx *types.Transaction) (*Response, error) { func (client *Client) SendTransactionSync(privkey string, tx *types33.Transaction) (*Response, error) {
// 签名 // 签名
hexbytes, _ := types.FromHex(privkey) hexbytes, _ := util.FromHex(privkey)
_, err := sdk.Sign(tx, hexbytes, crypto.SECP256K1, nil) _, err := Sign(tx, hexbytes, crypto.SECP256K1, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
signedTx := types.ToHexPrefix(types.Encode(tx)) signedTx := util.ToHexPrefix(util.Encode(tx))
var res string var res string
send := &RawParm{ send := &RawParm{
Token: "BTY", Token: "BTY",
...@@ -201,7 +203,7 @@ func (client *Client) SendTransactionSync(privkey string, tx *types.Transaction) ...@@ -201,7 +203,7 @@ func (client *Client) SendTransactionSync(privkey string, tx *types.Transaction)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &Response{OK: true, Message: res, Data: types.Encode(tx)}, nil return &Response{OK: true, Message: res, Data: util.Encode(tx)}, nil
} }
// QueryTransaction 查询交易 // QueryTransaction 查询交易
...@@ -229,7 +231,7 @@ func (client *Client) QueryLastHeader() (*Header, error) { ...@@ -229,7 +231,7 @@ func (client *Client) QueryLastHeader() (*Header, error) {
func (client *Client) QueryBlockHash(height int64) (*ReplyHash, error) { func (client *Client) QueryBlockHash(height int64) (*ReplyHash, error) {
var res ReplyHash var res ReplyHash
params := types.ReqInt{ params := types33.ReqInt{
Height: height, Height: height,
} }
err := client.Call(Chain33_GetBlockHash, params, &res) err := client.Call(Chain33_GetBlockHash, params, &res)
...@@ -273,7 +275,7 @@ func (client *Client) QueryMainNetIsSync() (bool, error) { ...@@ -273,7 +275,7 @@ func (client *Client) QueryMainNetIsSync() (bool, error) {
func (client *Client) QueryNetInfo() (*NodeNetinfo, error) { func (client *Client) QueryNetInfo() (*NodeNetinfo, error) {
var res NodeNetinfo var res NodeNetinfo
params := types.ReqNil{} params := types33.ReqNil{}
err := client.Call(Chain33_GetNetInfo, params, &res) err := client.Call(Chain33_GetNetInfo, params, &res)
if err != nil { if err != nil {
return nil, err return nil, err
...@@ -283,7 +285,7 @@ func (client *Client) QueryNetInfo() (*NodeNetinfo, error) { ...@@ -283,7 +285,7 @@ func (client *Client) QueryNetInfo() (*NodeNetinfo, error) {
func (client *Client) QueryMempool() (*ReplyTxList, error) { func (client *Client) QueryMempool() (*ReplyTxList, error) {
var res ReplyTxList var res ReplyTxList
params := types.ReqNil{} params := types33.ReqNil{}
err := client.Call(Chain33_GetMempool, params, &res) err := client.Call(Chain33_GetMempool, params, &res)
if err != nil { if err != nil {
return nil, err return nil, err
......
package rpc package rpc
import "encoding/json" import (
"encoding/json"
"errors"
types33 "github.com/33cn/chain33/types"
"gitlab.33.cn/link33/sidecar-client-chain33/crypto"
"gitlab.33.cn/link33/sidecar-client-chain33/crypto/ed25519"
"gitlab.33.cn/link33/sidecar-client-chain33/crypto/gm"
"gitlab.33.cn/link33/sidecar-client-chain33/util"
)
// RawParm defines raw parameter command // RawParm defines raw parameter command
type RawParm struct { type RawParm struct {
...@@ -365,3 +374,48 @@ type CallFunc struct { ...@@ -365,3 +374,48 @@ type CallFunc struct {
Func string `json:"func"` Func string `json:"func"`
Args [][]byte `json:"args"` Args [][]byte `json:"args"`
} }
func Sign(tx *types33.Transaction, privateKey []byte, signType string, uid []byte) (*types33.Transaction, error) {
if signType == "" {
signType = crypto.SECP256K1
}
tx.Signature = nil
if signType == crypto.SECP256K1 {
pub := crypto.PubKeyFromPrivate(privateKey)
data := util.Encode(tx)
signature := crypto.Sign(data, privateKey)
tx.Signature = &types33.Signature{
Ty: 1,
Pubkey: pub,
Signature: signature,
}
} else if signType == crypto.SM2 {
pub := gm.PubKeyFromPrivate(privateKey)
data := util.Encode(tx)
signature, err := gm.SM2Sign(data, privateKey, uid)
if err != nil {
return nil, err
}
tx.Signature = &types33.Signature{
Ty: 258,
Pubkey: pub,
Signature: signature,
}
} else if signType == crypto.ED25519 {
pub := ed25519.MakePublicKey(privateKey)
data := util.Encode(tx)
signature := ed25519.Sign(data, privateKey)
tx.Signature = &types33.Signature{
Ty: 2,
Pubkey: pub,
Signature: signature,
}
} else {
return nil, errors.New("sign type not support")
}
return tx, nil
}
...@@ -16,13 +16,26 @@ type Config struct { ...@@ -16,13 +16,26 @@ type Config struct {
Services []Service `mapstructure:"services" json:"services"` Services []Service `mapstructure:"services" json:"services"`
} }
type DB struct {
// 数据存储格式名称,目前支持mavl,kvdb,kvmvcc,mpt
Name string `json:"name,omitempty"`
// 数据存储驱动类别,目前支持leveldb,goleveldb,memdb,gobadgerdb,ssdb,pegasus
Driver string `json:"driver,omitempty"`
// 数据文件存储路径
DbPath string `json:"dbPath,omitempty"`
// Cache大小
DbCache int32 `json:"dbCache,omitempty"`
}
type Chain33 struct { type Chain33 struct {
Addr string `toml:"addr" json:"addr"` Addr string `toml:"addr" json:"addr"`
Name string `toml:"name" json:"name"` Name string `toml:"name" json:"name"`
PrivateKey string `mapstructure:"private_key" toml:"private_key" json:"private_key"`
ChainID string `mapstructure:"chain_id" json:"chain_id"`
DB *DB `json:"db,omitempty"`
EventFilter string `mapstructure:"event_filter" toml:"event_filter" json:"event_filter"` EventFilter string `mapstructure:"event_filter" toml:"event_filter" json:"event_filter"`
PrivateKey string `mapstructure:"private_key" toml:"private_key" json:"private_key"`
TimeoutHeight int64 `mapstructure:"timeout_height" json:"timeout_height"` TimeoutHeight int64 `mapstructure:"timeout_height" json:"timeout_height"`
ChainID string `mapstructure:"chain_id" json:"chain_id"`
} }
type Service struct { type Service struct {
...@@ -36,7 +49,14 @@ func DefaultConfig() *Config { ...@@ -36,7 +49,14 @@ func DefaultConfig() *Config {
Chain33: Chain33{ Chain33: Chain33{
Addr: "40.125.164.122:8801", Addr: "40.125.164.122:8801",
Name: "chain33", Name: "chain33",
DB: &DB{
Name: "blockchain",
Driver: "leveldb",
DbPath: "./blockchain",
DbCache: 100,
},
}, },
Services: nil, Services: nil,
} }
} }
......
package crypto
import (
"crypto/sha256"
"fmt"
"github.com/mr-tron/base58/base58"
)
// 不同币种的前缀版本号
var coinPrefix = map[string][]byte{
"BTC": {0x00},
"BCH": {0x00},
"BTY": {0x00},
"LTC": {0x30},
"ZEC": {0x1c, 0xb8},
"USDT": {0x00},
}
var addrSeed = []byte("address seed bytes for public key")
// MaxExecNameLength 执行器名最大长度
const MaxExecNameLength = 100
func PubKeyToAddress(pub []byte) (addr string, err error) {
if len(pub) != 33 && len(pub) != 65 { // 压缩格式 与 非压缩格式
return "", fmt.Errorf("invalid public key byte")
}
// 添加版本号
hash160res := append(coinPrefix["BTY"], Rimp160(pub)...)
// 添加校验码
cksum := checksum(hash160res)
address := append(hash160res, cksum[:]...)
// 地址进行base58编码
addr = base58.Encode(address)
return
}
// checksum: first four bytes of double-SHA256.
func checksum(input []byte) (cksum [4]byte) {
h := sha256.New()
_, err := h.Write(input)
if err != nil {
return
}
intermediateHash := h.Sum(nil)
h.Reset()
_, err = h.Write(intermediateHash)
if err != nil {
return
}
finalHash := h.Sum(nil)
copy(cksum[:], finalHash[:])
return
}
func GetExecAddress(name string) string {
if len(name) > MaxExecNameLength {
panic("name too long")
}
var bname [200]byte
buf := append(bname[:0], addrSeed...)
buf = append(buf, []byte(name)...)
pub := Sha2Sum(buf)
var ad [25]byte
ad[0] = 0
copy(ad[1:21], Rimp160(pub))
sh := Sha2Sum(ad[0:21])
checksum := make([]byte, 4)
copy(checksum, sh[:4])
copy(ad[21:25], checksum[:])
addr := base58.Encode(ad[:])
return addr
}
package crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
const (
AESPrivateKeyLength = 16
)
func pkcs7Padding(src []byte) []byte {
padding := aes.BlockSize - len(src)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func aesCBCEncrypt(key, s []byte) ([]byte, error) {
return aesCBCEncryptWithRand(rand.Reader, key, s)
}
func aesCBCEncryptWithRand(prng io.Reader, key, s []byte) ([]byte, error) {
if len(s)%aes.BlockSize != 0 {
return nil, errors.New("Invalid plaintext. It must be a multiple of the block size")
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(s))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(prng, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], s)
return ciphertext, nil
}
func aesCBCDecrypt(key, src []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(src) < aes.BlockSize {
return nil, errors.New("Invalid ciphertext. It must be a multiple of the block size")
}
iv := src[:aes.BlockSize]
src = src[aes.BlockSize:]
if len(src)%aes.BlockSize != 0 {
return nil, errors.New("Invalid ciphertext. It must be a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(src, src)
return src, nil
}
func pkcs7UnPadding(src []byte) ([]byte, error) {
length := len(src)
unpadding := int(src[length-1])
if unpadding > aes.BlockSize || unpadding == 0 {
return nil, errors.New("Invalid pkcs7 padding (unpadding > aes.BlockSize || unpadding == 0)")
}
pad := src[len(src)-unpadding:]
for i := 0; i < unpadding; i++ {
if pad[i] != byte(unpadding) {
return nil, errors.New("Invalid pkcs7 padding (pad[i] != unpadding)")
}
}
return src[:(length - unpadding)], nil
}
func AESCBCPKCS7Encrypt(key, src []byte) ([]byte, error) {
tmp := pkcs7Padding(src)
return aesCBCEncrypt(key, tmp)
}
func AESCBCPKCS7Decrypt(key, src []byte) ([]byte, error) {
pt, err := aesCBCDecrypt(key, src)
if err == nil {
return pkcs7UnPadding(pt)
}
return nil, err
}
func GenetateAESKey() []byte {
return getRandBytes(AESPrivateKeyLength)
}
package crypto
import (
"bytes"
"crypto/rand"
secp256k1 "github.com/btcsuite/btcd/btcec"
)
var (
SECP256K1 = "secp256k1"
SM2 = "sm2"
ED25519 = "ed25519" // TODO
)
func GeneratePrivateKey() []byte {
privKeyBytes := make([]byte, 32)
for {
key := getRandBytes(32)
if bytes.Compare(key, secp256k1.S256().Params().N.Bytes()) >= 0 {
continue
}
copy(privKeyBytes[:], key)
break
}
priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKeyBytes[:])
copy(privKeyBytes[:], priv.Serialize())
return privKeyBytes
}
func PubKeyFromPrivate(privKey []byte) []byte {
_, pub := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:])
pubSecp256k1 := make([]byte, 33)
copy(pubSecp256k1[:], pub.SerializeCompressed())
return pubSecp256k1
}
func Sign(msg []byte, privKey []byte) []byte {
priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:])
sig, err := priv.Sign(Sha256(msg))
if err != nil {
panic("Error signing secp256k1" + err.Error())
}
return sig.Serialize()
}
func PrivateFromByte(privKey []byte) *secp256k1.PrivateKey {
priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey[:])
return priv
}
func PublicFromByte(pubKey []byte) *secp256k1.PublicKey {
pub, _ := secp256k1.ParsePubKey(pubKey, secp256k1.S256())
return pub
}
func getRandBytes(numBytes int) []byte {
b := make([]byte, numBytes)
_, err := rand.Read(b)
if err != nil {
panic("Panic on a Crisis" + err.Error())
}
return b
}
package crypto
//func EncodeCertToSignature(signBytes, cert, uid []byte) []byte {
// var certSignature types.CertSignature
// certSignature.Cert = cert
// certSignature.Signature = signBytes
// certSignature.Uid = uid
//
// return types.Encode(&certSignature)
//}
package crypto
import (
"fmt"
"testing"
"gitlab.33.cn/link33/sidecar-client-chain33/util"
"github.com/stretchr/testify/assert"
"gitlab.33.cn/link33/sidecar-client-chain33/crypto/ed25519"
"gitlab.33.cn/link33/sidecar-client-chain33/crypto/gm"
)
func TestAES(t *testing.T) {
text := "hello aes"
key := getRandBytes(16)
cipherText, err := AESCBCPKCS7Encrypt(key, []byte(text))
if err != nil {
fmt.Println(err)
return
}
cipher, err := AESCBCPKCS7Decrypt(key, cipherText)
if err != nil {
fmt.Println(err)
return
}
assert.Equal(t, text, string(cipher))
}
func TestSign(t *testing.T) {
priv, _ := util.FromHex("0xc2b31057b8692a56c7dd18199df71c1d21b781c0b6858c52997c9dbf778e8550")
msg := []byte("sign test")
sig := Sign(msg, priv)
fmt.Printf("sig = %x\n", sig)
}
func TestSM2(t *testing.T) {
priv, pub := gm.GenerateKey()
fmt.Println(priv)
fmt.Println(pub)
fmt.Println(util.ToHex(priv))
fmt.Println(util.ToHex(pub))
msg := []byte("sign test")
sig, _ := gm.SM2Sign(msg, priv, nil)
fmt.Printf("sig = %x\n", sig)
result := gm.SM2Verify(pub, msg, nil, sig)
assert.Equal(t, true, result)
}
func TestSM4(t *testing.T) {
key := []byte{0x1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}
fmt.Printf("key = %v\n", key)
data := []byte{0x1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}
fmt.Printf("data = %x\n", data)
d0 := gm.SM4Encrypt(key, data)
fmt.Printf("d0 = %x\n", d0)
d1 := gm.SM4Decrypt(key, d0)
fmt.Printf("d1 = %x\n", d1)
assert.Equal(t, data, d1)
}
func TestAddress(t *testing.T) {
priv, _ := util.FromHex("0xc2b31057b8692a56c7dd18199df71c1d21b781c0b6858c52997c9dbf778e8550")
pub := PubKeyFromPrivate(priv)
fmt.Println(util.ToHex(pub))
addr, err := PubKeyToAddress(pub)
if err != nil {
panic(err)
}
fmt.Println(addr)
}
func TestKDF(t *testing.T) {
keyf := KDF([]byte("kdf test"), 16)
fmt.Println(util.ToHex(keyf))
assert.Equal(t, 16, len(keyf))
}
func TestED25519(t *testing.T) {
priv, pub, err := ed25519.GenerateKey()
if err != nil {
assert.Fail(t, err.Error())
}
fmt.Println(util.ToHex(pub))
msg := []byte("sign test")
sig := ed25519.Sign(priv, msg)
fmt.Printf("sig = %x\n", sig)
result := ed25519.Verify(pub, msg, sig)
assert.Equal(t, true, result)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ed25519 implements the Ed25519 signature algorithm. See
// http://ed25519.cr.yp.to/.
package ed25519
// This code is a port of the public domain, "ref10" implementation of ed25519
// from SUPERCOP.
import (
"crypto/rand"
"crypto/sha512"
"crypto/subtle"
"gitlab.33.cn/link33/sidecar-client-chain33/crypto/ed25519/edwards25519"
)
// const
const (
PublicKeySize = 32
PrivateKeySize = 64
SignatureSize = 64
)
// GenerateKey generates a public/private key pair using randomness from rand.
func GenerateKey() ([]byte, []byte, error) {
privateKey := make([]byte, PrivateKeySize)
_, err := rand.Read(privateKey[:32])
if err != nil {
return nil, nil, err
}
publicKey := MakePublicKey(privateKey)
return privateKey, publicKey, nil
}
// MakePublicKey makes a publicKey from the first half of privateKey.
func MakePublicKey(privateKey []byte) []byte {
publicKey := new([PublicKeySize]byte)
h := sha512.New()
h.Write(privateKey[:32])
digest := h.Sum(nil)
digest[0] &= 248
digest[31] &= 127
digest[31] |= 64
var A edwards25519.ExtendedGroupElement
var hBytes [32]byte
copy(hBytes[:], digest)
edwards25519.GeScalarMultBase(&A, &hBytes)
A.ToBytes(publicKey)
pub := make([]byte, PublicKeySize)
copy(privateKey[32:], publicKey[:])
copy(pub[:], publicKey[:])
return pub
}
// Sign signs the message with privateKey and returns a signature.
func Sign(privateKey []byte, message []byte) []byte {
h := sha512.New()
h.Write(privateKey[:32])
var digest1, messageDigest, hramDigest [64]byte
var expandedSecretKey [32]byte
h.Sum(digest1[:0])
copy(expandedSecretKey[:], digest1[:])
expandedSecretKey[0] &= 248
expandedSecretKey[31] &= 63
expandedSecretKey[31] |= 64
h.Reset()
h.Write(digest1[32:])
h.Write(message)
h.Sum(messageDigest[:0])
var messageDigestReduced [32]byte
edwards25519.ScReduce(&messageDigestReduced, &messageDigest)
var R edwards25519.ExtendedGroupElement
edwards25519.GeScalarMultBase(&R, &messageDigestReduced)
var encodedR [32]byte
R.ToBytes(&encodedR)
h.Reset()
h.Write(encodedR[:])
h.Write(privateKey[32:])
h.Write(message)
h.Sum(hramDigest[:0])
var hramDigestReduced [32]byte
edwards25519.ScReduce(&hramDigestReduced, &hramDigest)
var s [32]byte
edwards25519.ScMulAdd(&s, &hramDigestReduced, &expandedSecretKey, &messageDigestReduced)
signature := make([]byte, SignatureSize)
copy(signature[:], encodedR[:])
copy(signature[32:], s[:])
return signature
}
// Verify returns true iff sig is a valid signature of message by publicKey.
func Verify(publicKey []byte, message []byte, sig []byte) bool {
if sig[63]&224 != 0 {
return false
}
pub := new([PublicKeySize]byte)
copy(pub[:], publicKey[:])
var A edwards25519.ExtendedGroupElement
if !A.FromBytes(pub) {
return false
}
edwards25519.FeNeg(&A.X, &A.X)
edwards25519.FeNeg(&A.T, &A.T)
h := sha512.New()
h.Write(sig[:32])
h.Write(publicKey[:])
h.Write(message)
var digest [64]byte
h.Sum(digest[:0])
var hReduced [32]byte
edwards25519.ScReduce(&hReduced, &digest)
var R edwards25519.ProjectiveGroupElement
var b [32]byte
copy(b[:], sig[32:])
edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b)
var checkR [32]byte
R.ToBytes(&checkR)
return subtle.ConstantTimeCompare(sig[:32], checkR[:]) == 1
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
package gm
import (
"bytes"
"crypto/elliptic"
"crypto/rand"
"fmt"
"math/big"
"github.com/btcsuite/btcd/btcec"
"github.com/tjfoc/gmsm/sm2"
)
const (
SM2PrivateKeyLength = 32
)
var DefaultUID = []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}
func getRandBytes(numBytes int) []byte {
b := make([]byte, numBytes)
_, err := rand.Read(b)
if err != nil {
panic("Panic on a Crisis" + err.Error())
}
return b
}
func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*sm2.PrivateKey, *sm2.PublicKey) {
x, y := curve.ScalarBaseMult(pk)
priv := &sm2.PrivateKey{
PublicKey: sm2.PublicKey{
Curve: curve,
X: x,
Y: y,
},
D: new(big.Int).SetBytes(pk),
}
return priv, &priv.PublicKey
}
func parsePubKey(pubKeyStr []byte) (key *sm2.PublicKey) {
return sm2.Decompress(pubKeyStr)
}
// SerializePublicKey 公钥序列化
func SerializePublicKey(p *sm2.PublicKey) []byte {
return sm2.Compress(p)
}
// SerializePrivateKey 私钥序列化
func SerializePrivateKey(p *sm2.PrivateKey) []byte {
b := make([]byte, 0, SM2PrivateKeyLength)
return paddedAppend(SM2PrivateKeyLength, b, p.D.Bytes())
}
func paddedAppend(size uint, dst, src []byte) []byte {
for i := 0; i < int(size)-len(src); i++ {
dst = append(dst, 0)
}
return append(dst, src...)
}
func canonicalizeInt(val *big.Int) []byte {
b := val.Bytes()
if len(b) == 0 {
b = []byte{0x00}
}
if b[0]&0x80 != 0 {
paddedBytes := make([]byte, len(b)+1)
copy(paddedBytes[1:], b)
b = paddedBytes
}
return b
}
func SerializeSignature(r, s *big.Int) []byte {
rb := canonicalizeInt(r)
sb := canonicalizeInt(s)
length := 6 + len(rb) + len(sb)
b := make([]byte, length)
b[0] = 0x30
b[1] = byte(length - 2)
b[2] = 0x02
b[3] = byte(len(rb))
offset := copy(b[4:], rb) + 4
b[offset] = 0x02
b[offset+1] = byte(len(sb))
copy(b[offset+2:], sb)
return b
}
func DeserializeSignature(sigStr []byte) (*big.Int, *big.Int, error) {
sig, err := btcec.ParseDERSignature(sigStr, sm2.P256Sm2())
if err != nil {
return nil, nil, err
}
return sig.R, sig.S, nil
}
func GenerateKey() ([]byte, []byte) {
privKeyBytes := [SM2PrivateKeyLength]byte{}
for {
key := getRandBytes(32)
if bytes.Compare(key, sm2.P256Sm2().Params().N.Bytes()) >= 0 {
continue
}
copy(privKeyBytes[:], key)
break
}
priv, pub := PrivKeyFromBytes(sm2.P256Sm2(), privKeyBytes[:])
return SerializePrivateKey(priv), SerializePublicKey(pub)
}
func SM2Sign(msg []byte, privateKey []byte, uid []byte) ([]byte, error) {
if uid == nil {
uid = DefaultUID
}
priv, _ := PrivKeyFromBytes(sm2.P256Sm2(), privateKey)
r, s, err := sm2.Sm2Sign(priv, msg, uid)
if err != nil {
return nil, err
}
return SerializeSignature(r, s), nil
}
func SM2Verify(publicKey []byte, msg []byte, uid []byte, sig []byte) bool {
if uid == nil {
uid = DefaultUID
}
pub := parsePubKey(publicKey[:])
r, s, err := DeserializeSignature(sig)
if err != nil {
fmt.Errorf("unmarshal sign failed:" + err.Error())
return false
}
return sm2.Sm2Verify(pub, msg, uid, r, s)
}
func SM2Encrypt(publicKey []byte, data []byte) ([]byte, error) {
pub := parsePubKey(publicKey[:])
return sm2.Encrypt(pub, data)
}
func SM2Decrypt(privateKey []byte, data []byte) ([]byte, error) {
priv, _ := PrivKeyFromBytes(sm2.P256Sm2(), privateKey)
return sm2.Decrypt(priv, data)
}
func PubKeyFromPrivate(privKey []byte) []byte {
_, pub := PrivKeyFromBytes(sm2.P256Sm2(), privKey)
return SerializePublicKey(pub)
}
package gm
import "github.com/tjfoc/gmsm/sm3"
// SM3Hash 加密算法
func SM3Hash(msg []byte) []byte {
c := sm3.New()
c.Write(msg)
return c.Sum(nil)
}
package gm
import (
"log"
"github.com/tjfoc/gmsm/sm4"
)
const (
SM4PrivateKeyLength = 16
)
func GenetateSM4Key() []byte {
return getRandBytes(SM4PrivateKeyLength)
}
func SM4Encrypt(key []byte, data []byte) []byte {
c, err := sm4.NewCipher(key)
if err != nil {
log.Fatal(err)
}
cipher := make([]byte, 16)
c.Encrypt(cipher, data)
return cipher
}
func SM4Decrypt(key []byte, data []byte) []byte {
c, err := sm4.NewCipher(key)
if err != nil {
log.Fatal(err)
}
cipher := make([]byte, 16)
c.Decrypt(cipher, data)
return cipher
}
package crypto
import (
"crypto/sha256"
"encoding/binary"
"golang.org/x/crypto/ripemd160"
)
func Sha256(b []byte) []byte {
hasher := sha256.New()
hasher.Write(b)
return hasher.Sum(nil)
}
func Sha2Sum(b []byte) []byte {
tmp := sha256.Sum256(b)
tmp = sha256.Sum256(tmp[:])
return tmp[:]
}
func rimpHash(in []byte, out []byte) {
sha := sha256.New()
_, err := sha.Write(in)
if err != nil {
return
}
rim := ripemd160.New()
_, err = rim.Write(sha.Sum(nil)[:])
if err != nil {
return
}
copy(out, rim.Sum(nil))
}
// Rimp160 Returns hash: RIMP160( SHA256( data ) )
// Where possible, using RimpHash() should be a bit faster
func Rimp160(b []byte) []byte {
out := make([]byte, 20)
rimpHash(b, out[:])
return out[:]
}
func intToBytes(x int) []byte {
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, uint32(x))
return buf
}
func KDF(x []byte, length int) []byte {
var c []byte
ct := 1
h := sha256.New()
for i, j := 0, (length+31)/32; i < j; i++ {
h.Reset()
h.Write(x)
h.Write(intToBytes(ct))
hash := h.Sum(nil)
if i+1 == j && length%32 != 0 {
c = append(c, hash[:length%32]...)
} else {
c = append(c, hash...)
}
ct++
}
return c
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package sha3 implements the SHA-3 fixed-output-length hash functions and
// the SHAKE variable-output-length hash functions defined by FIPS-202.
//
// Both types of hash function use the "sponge" construction and the Keccak
// permutation. For a detailed specification see http://keccak.noekeon.org/
//
//
// Guidance
//
// If you aren't sure what function you need, use SHAKE256 with at least 64
// bytes of output. The SHAKE instances are faster than the SHA3 instances;
// the latter have to allocate memory to conform to the hash.Hash interface.
//
// If you need a secret-key MAC (message authentication code), prepend the
// secret key to the input, hash with SHAKE256 and read at least 32 bytes of
// output.
//
//
// Security strengths
//
// The SHA3-x (x equals 224, 256, 384, or 512) functions have a security
// strength against preimage attacks of x bits. Since they only produce "x"
// bits of output, their collision-resistance is only "x/2" bits.
//
// The SHAKE-256 and -128 functions have a generic security strength of 256 and
// 128 bits against all attacks, provided that at least 2x bits of their output
// is used. Requesting more than 64 or 32 bytes of output, respectively, does
// not increase the collision-resistance of the SHAKE functions.
//
//
// The sponge construction
//
// A sponge builds a pseudo-random function from a public pseudo-random
// permutation, by applying the permutation to a state of "rate + capacity"
// bytes, but hiding "capacity" of the bytes.
//
// A sponge starts out with a zero state. To hash an input using a sponge, up
// to "rate" bytes of the input are XORed into the sponge's state. The sponge
// is then "full" and the permutation is applied to "empty" it. This process is
// repeated until all the input has been "absorbed". The input is then padded.
// The digest is "squeezed" from the sponge in the same way, except that output
// output is copied out instead of input being XORed in.
//
// A sponge is parameterized by its generic security strength, which is equal
// to half its capacity; capacity + rate is equal to the permutation's width.
// Since the KeccakF-1600 permutation is 1600 bits (200 bytes) wide, this means
// that the security strength of a sponge instance is equal to (1600 - bitrate) / 2.
//
//
// Recommendations
//
// The SHAKE functions are recommended for most new uses. They can produce
// output of arbitrary length. SHAKE256, with an output length of at least
// 64 bytes, provides 256-bit security against all attacks. The Keccak team
// recommends it for most applications upgrading from SHA2-512. (NIST chose a
// much stronger, but much slower, sponge instance for SHA3-512.)
//
// The SHA-3 functions are "drop-in" replacements for the SHA-2 functions.
// They produce output of the same length, with the same security strengths
// against all attacks. This means, in particular, that SHA3-256 only has
// 128-bit collision resistance, because its output length is 32 bytes.
package sha3
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
// This file provides functions for creating instances of the SHA-3
// and SHAKE hash functions, as well as utility functions for hashing
// bytes.
import (
"hash"
)
// NewKeccak256 creates a new Keccak-256 hash.
func NewKeccak256() hash.Hash { return &state{rate: 136, outputLen: 32, dsbyte: 0x01} }
// NewKeccak512 creates a new Keccak-512 hash.
func NewKeccak512() hash.Hash { return &state{rate: 72, outputLen: 64, dsbyte: 0x01} }
// New224 creates a new SHA3-224 hash.
// Its generic security strength is 224 bits against preimage attacks,
// and 112 bits against collision attacks.
func New224() hash.Hash { return &state{rate: 144, outputLen: 28, dsbyte: 0x06} }
// New256 creates a new SHA3-256 hash.
// Its generic security strength is 256 bits against preimage attacks,
// and 128 bits against collision attacks.
func New256() hash.Hash { return &state{rate: 136, outputLen: 32, dsbyte: 0x06} }
// New384 creates a new SHA3-384 hash.
// Its generic security strength is 384 bits against preimage attacks,
// and 192 bits against collision attacks.
func New384() hash.Hash { return &state{rate: 104, outputLen: 48, dsbyte: 0x06} }
// New512 creates a new SHA3-512 hash.
// Its generic security strength is 512 bits against preimage attacks,
// and 256 bits against collision attacks.
func New512() hash.Hash { return &state{rate: 72, outputLen: 64, dsbyte: 0x06} }
// NewLegacyKeccak256 creates a new Keccak-256 hash.
//
// Only use this function if you require compatibility with an existing cryptosystem
// that uses non-standard padding. All other users should use New256 instead.
func NewLegacyKeccak256() hash.Hash { return &state{rate: 136, outputLen: 32, dsbyte: 0x01} }
// Sum224 returns the SHA3-224 digest of the data.
func Sum224(data []byte) (digest [28]byte) {
h := New224()
h.Write(data)
h.Sum(digest[:0])
return
}
// Sum256 returns the SHA3-256 digest of the data.
func Sum256(data []byte) (digest [32]byte) {
h := New256()
h.Write(data)
h.Sum(digest[:0])
return
}
// Sum384 returns the SHA3-384 digest of the data.
func Sum384(data []byte) (digest [48]byte) {
h := New384()
h.Write(data)
h.Sum(digest[:0])
return
}
// Sum512 returns the SHA3-512 digest of the data.
func Sum512(data []byte) (digest [64]byte) {
h := New512()
h.Write(data)
h.Sum(digest[:0])
return
}
// KeccakSum256 returns the Keccak-256 digest of the data.
func KeccakSum256(data []byte) (digest [32]byte) {
h := NewKeccak256()
h.Write(data)
h.Sum(digest[:0])
return
}
// KeccakSum512 returns the Keccak-512 digest of the data.
func KeccakSum512(data []byte) (digest [32]byte) {
h := NewKeccak512()
h.Write(data)
h.Sum(digest[:0])
return
}
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build amd64 && !appengine && !gccgo
// +build amd64,!appengine,!gccgo
package sha3
// This function is implemented in keccakf_amd64.s.
//go:noescape
func keccakF1600(a *[25]uint64)
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.4
// +build go1.4
package sha3
import (
"crypto"
)
func init() {
crypto.RegisterHash(crypto.SHA3_224, New224)
crypto.RegisterHash(crypto.SHA3_256, New256)
crypto.RegisterHash(crypto.SHA3_384, New384)
crypto.RegisterHash(crypto.SHA3_512, New512)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
// spongeDirection indicates the direction bytes are flowing through the sponge.
type spongeDirection int
const (
// spongeAbsorbing indicates that the sponge is absorbing input.
spongeAbsorbing spongeDirection = iota
// spongeSqueezing indicates that the sponge is being squeezed.
spongeSqueezing
)
const (
// maxRate is the maximum size of the internal buffer. SHAKE-256
// currently needs the largest buffer.
maxRate = 168
)
type state struct {
// Generic sponge components.
a [25]uint64 // main state of the hash
buf []byte // points into storage
rate int // the number of bytes of state to use
// dsbyte contains the "domain separation" bits and the first bit of
// the padding. Sections 6.1 and 6.2 of [1] separate the outputs of the
// SHA-3 and SHAKE functions by appending bitstrings to the message.
// Using a little-endian bit-ordering convention, these are "01" for SHA-3
// and "1111" for SHAKE, or 00000010b and 00001111b, respectively. Then the
// padding rule from section 5.1 is applied to pad the message to a multiple
// of the rate, which involves adding a "1" bit, zero or more "0" bits, and
// a final "1" bit. We merge the first "1" bit from the padding into dsbyte,
// giving 00000110b (0x06) and 00011111b (0x1f).
// [1] http://csrc.nist.gov/publications/drafts/fips-202/fips_202_draft.pdf
// "Draft FIPS 202: SHA-3 Standard: Permutation-Based Hash and
// Extendable-Output Functions (May 2014)"
dsbyte byte
storage [maxRate]byte
// Specific to SHA-3 and SHAKE.
outputLen int // the default output size in bytes
state spongeDirection // whether the sponge is absorbing or squeezing
}
// BlockSize returns the rate of sponge underlying this hash function.
func (d *state) BlockSize() int { return d.rate }
// Size returns the output size of the hash function in bytes.
func (d *state) Size() int { return d.outputLen }
// Reset clears the internal state by zeroing the sponge state and
// the byte buffer, and setting Sponge.state to absorbing.
func (d *state) Reset() {
// Zero the permutation's state.
for i := range d.a {
d.a[i] = 0
}
d.state = spongeAbsorbing
d.buf = d.storage[:0]
}
func (d *state) clone() *state {
ret := *d
if ret.state == spongeAbsorbing {
ret.buf = ret.storage[:len(ret.buf)]
} else {
ret.buf = ret.storage[d.rate-cap(d.buf) : d.rate]
}
return &ret
}
// permute applies the KeccakF-1600 permutation. It handles
// any input-output buffering.
func (d *state) permute() {
switch d.state {
case spongeAbsorbing:
// If we're absorbing, we need to xor the input into the state
// before applying the permutation.
xorIn(d, d.buf)
d.buf = d.storage[:0]
keccakF1600(&d.a)
case spongeSqueezing:
// If we're squeezing, we need to apply the permutatin before
// copying more output.
keccakF1600(&d.a)
d.buf = d.storage[:d.rate]
copyOut(d, d.buf)
}
}
// pads appends the domain separation bits in dsbyte, applies
// the multi-bitrate 10..1 padding rule, and permutes the state.
func (d *state) padAndPermute(dsbyte byte) {
if d.buf == nil {
d.buf = d.storage[:0]
}
// Pad with this instance's domain-separator bits. We know that there's
// at least one byte of space in d.buf because, if it were full,
// permute would have been called to empty it. dsbyte also contains the
// first one bit for the padding. See the comment in the state struct.
d.buf = append(d.buf, dsbyte)
zerosStart := len(d.buf)
d.buf = d.storage[:d.rate]
for i := zerosStart; i < d.rate; i++ {
d.buf[i] = 0
}
// This adds the final one bit for the padding. Because of the way that
// bits are numbered from the LSB upwards, the final bit is the MSB of
// the last byte.
d.buf[d.rate-1] ^= 0x80
// Apply the permutation
d.permute()
d.state = spongeSqueezing
d.buf = d.storage[:d.rate]
copyOut(d, d.buf)
}
// Write absorbs more data into the hash's state. It produces an error
// if more data is written to the ShakeHash after writing
func (d *state) Write(p []byte) (written int, err error) {
if d.state != spongeAbsorbing {
panic("sha3: write to sponge after read")
}
if d.buf == nil {
d.buf = d.storage[:0]
}
written = len(p)
for len(p) > 0 {
if len(d.buf) == 0 && len(p) >= d.rate {
// The fast path; absorb a full "rate" bytes of input and apply the permutation.
xorIn(d, p[:d.rate])
p = p[d.rate:]
keccakF1600(&d.a)
} else {
// The slow path; buffer the input until we can fill the sponge, and then xor it in.
todo := d.rate - len(d.buf)
if todo > len(p) {
todo = len(p)
}
d.buf = append(d.buf, p[:todo]...)
p = p[todo:]
// If the sponge is full, apply the permutation.
if len(d.buf) == d.rate {
d.permute()
}
}
}
return
}
// Read squeezes an arbitrary number of bytes from the sponge.
func (d *state) Read(out []byte) (n int, err error) {
// If we're still absorbing, pad and apply the permutation.
if d.state == spongeAbsorbing {
d.padAndPermute(d.dsbyte)
}
n = len(out)
// Now, do the squeezing.
for len(out) > 0 {
n := copy(out, d.buf)
d.buf = d.buf[n:]
out = out[n:]
// Apply the permutation if we've squeezed the sponge dry.
if len(d.buf) == 0 {
d.permute()
}
}
return
}
// Sum applies padding to the hash state and then squeezes out the desired
// number of output bytes.
func (d *state) Sum(in []byte) []byte {
// Make a copy of the original hash so that caller can keep writing
// and summing.
dup := d.clone()
hash := make([]byte, dup.outputLen)
dup.Read(hash)
return append(in, hash...)
}
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
// This file defines the ShakeHash interface, and provides
// functions for creating SHAKE instances, as well as utility
// functions for hashing bytes to arbitrary-length output.
import (
"io"
)
// ShakeHash defines the interface to hash functions that
// support arbitrary-length output.
type ShakeHash interface {
// Write absorbs more data into the hash's state. It panics if input is
// written to it after output has been read from it.
io.Writer
// Read reads more output from the hash; reading affects the hash's
// state. (ShakeHash.Read is thus very different from Hash.Sum)
// It never returns an error.
io.Reader
// Clone returns a copy of the ShakeHash in its current state.
Clone() ShakeHash
// Reset resets the ShakeHash to its initial state.
Reset()
}
func (d *state) Clone() ShakeHash {
return d.clone()
}
// NewShake128 creates a new SHAKE128 variable-output-length ShakeHash.
// Its generic security strength is 128 bits against all attacks if at
// least 32 bytes of its output are used.
func NewShake128() ShakeHash { return &state{rate: 168, dsbyte: 0x1f} }
// NewShake256 creates a new SHAKE128 variable-output-length ShakeHash.
// Its generic security strength is 256 bits against all attacks if
// at least 64 bytes of its output are used.
func NewShake256() ShakeHash { return &state{rate: 136, dsbyte: 0x1f} }
// ShakeSum128 writes an arbitrary-length digest of data into hash.
func ShakeSum128(hash, data []byte) {
h := NewShake128()
h.Write(data)
h.Read(hash)
}
// ShakeSum256 writes an arbitrary-length digest of data into hash.
func ShakeSum256(hash, data []byte) {
h := NewShake256()
h.Write(data)
h.Read(hash)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build (!amd64 && !386 && !ppc64le) || appengine
// +build !amd64,!386,!ppc64le appengine
package sha3
var (
xorIn = xorInGeneric
copyOut = copyOutGeneric
xorInUnaligned = xorInGeneric
copyOutUnaligned = copyOutGeneric
)
// const xorImplementationUnaligned = "generic"
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sha3
import "encoding/binary"
// xorInGeneric xors the bytes in buf into the state; it
// makes no non-portable assumptions about memory layout
// or alignment.
func xorInGeneric(d *state, buf []byte) {
n := len(buf) / 8
for i := 0; i < n; i++ {
a := binary.LittleEndian.Uint64(buf)
d.a[i] ^= a
buf = buf[8:]
}
}
// copyOutGeneric copies ulint64s to a byte buffer.
func copyOutGeneric(d *state, b []byte) {
for i := 0; len(b) >= 8; i++ {
binary.LittleEndian.PutUint64(b, d.a[i])
b = b[8:]
}
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build (amd64 || 386 || ppc64le) && !appengine
// +build amd64 386 ppc64le
// +build !appengine
package sha3
import "unsafe"
func xorInUnaligned(d *state, buf []byte) {
bw := (*[maxRate / 8]uint64)(unsafe.Pointer(&buf[0]))
n := len(buf)
if n >= 72 {
d.a[0] ^= bw[0]
d.a[1] ^= bw[1]
d.a[2] ^= bw[2]
d.a[3] ^= bw[3]
d.a[4] ^= bw[4]
d.a[5] ^= bw[5]
d.a[6] ^= bw[6]
d.a[7] ^= bw[7]
d.a[8] ^= bw[8]
}
if n >= 104 {
d.a[9] ^= bw[9]
d.a[10] ^= bw[10]
d.a[11] ^= bw[11]
d.a[12] ^= bw[12]
}
if n >= 136 {
d.a[13] ^= bw[13]
d.a[14] ^= bw[14]
d.a[15] ^= bw[15]
d.a[16] ^= bw[16]
}
if n >= 144 {
d.a[17] ^= bw[17]
}
if n >= 168 {
d.a[18] ^= bw[18]
d.a[19] ^= bw[19]
d.a[20] ^= bw[20]
}
}
func copyOutUnaligned(d *state, buf []byte) {
ab := (*[maxRate]uint8)(unsafe.Pointer(&d.a[0]))
copy(buf, ab[:])
}
var (
xorIn = xorInUnaligned
copyOut = copyOutUnaligned
)
// const xorImplementationUnaligned = "unaligned"
package evmxgo
import "testing"
func bytesPrefix(prefix []byte) []byte {
var limit []byte
for i := len(prefix) - 1; i >= 0; i-- {
c := prefix[i]
if c < 0xff {
limit = make([]byte, i+1)
copy(limit, prefix)
limit[i] = c + 1
break
}
}
return limit
}
func TestRangGet(t *testing.T) {
ret := bytesPrefix([]byte("abcffkopk"))
t.Log(ret)
}
...@@ -6,12 +6,14 @@ import ( ...@@ -6,12 +6,14 @@ import (
"os" "os"
"time" "time"
"github.com/33cn/chain33/common/db"
types33 "github.com/33cn/chain33/types"
evmxgotypes "github.com/33cn/plugin/plugin/dapp/evmxgo/types" evmxgotypes "github.com/33cn/plugin/plugin/dapp/evmxgo/types"
"github.com/hashicorp/go-hclog" "github.com/hashicorp/go-hclog"
"gitlab.33.cn/link33/chain33-sdk-go/types"
"gitlab.33.cn/link33/sidecar-client-chain33/client/rpc" "gitlab.33.cn/link33/sidecar-client-chain33/client/rpc"
"gitlab.33.cn/link33/sidecar-client-chain33/config" "gitlab.33.cn/link33/sidecar-client-chain33/config"
typess "gitlab.33.cn/link33/sidecar-client-chain33/types" typess "gitlab.33.cn/link33/sidecar-client-chain33/types"
"gitlab.33.cn/link33/sidecar-client-chain33/util"
"gitlab.33.cn/link33/sidecar/model/pb" "gitlab.33.cn/link33/sidecar/model/pb"
"gitlab.33.cn/link33/sidecar/pkg/plugins" "gitlab.33.cn/link33/sidecar/pkg/plugins"
"gitlab.33.cn/link33/sidecar/tool" "gitlab.33.cn/link33/sidecar/tool"
...@@ -37,8 +39,13 @@ const ( ...@@ -37,8 +39,13 @@ const (
execer = "evmxgo" execer = "evmxgo"
) )
// 存储索引
const (
index = "lock_mint"
)
var logger = hclog.New(&hclog.LoggerOptions{ var logger = hclog.New(&hclog.LoggerOptions{
Name: "chain33-client", Name: "chain33-client-" + PluginName,
Output: os.Stderr, Output: os.Stderr,
Level: hclog.Trace, Level: hclog.Trace,
}) })
...@@ -49,21 +56,13 @@ type Evmxgo struct { ...@@ -49,21 +56,13 @@ type Evmxgo struct {
eventC chan *pb.IBTP // 发送给sidecar eventC chan *pb.IBTP // 发送给sidecar
appChainID string appChainID string
toChainID string toChainID string
name string ticker *time.Ticker
done chan bool
ticker *time.Ticker client *rpc.Client
pk string // 签名,仅仅是和当前链挂钩的私钥。
serviceMeta map[string]*pb.Interchain height int64 // 已经解析的高度。1、初始化时设置; 2、服务每次重启后设置
done chan bool
timeoutHeight int64
// config *main.Config
client *rpc.Client
pk string // 签名,仅仅是和当前链挂钩的私钥。
height int64 // 已经解析的高度。1、初始化时设置; 2、服务每次重启后设置
// 记录已完成的hashID、高度等信息。 // 记录已完成的hashID、高度等信息。
db *KVDBList
} }
func (e *Evmxgo) Start() error { func (e *Evmxgo) Start() error {
...@@ -73,6 +72,7 @@ func (e *Evmxgo) Start() error { ...@@ -73,6 +72,7 @@ func (e *Evmxgo) Start() error {
} }
func (e *Evmxgo) Stop() error { func (e *Evmxgo) Stop() error {
e.db.Close()
e.ticker.Stop() e.ticker.Stop()
e.done <- true e.done <- true
return nil return nil
...@@ -96,8 +96,32 @@ func (e *Evmxgo) ID() string { ...@@ -96,8 +96,32 @@ func (e *Evmxgo) ID() string {
return ID return ID
} }
// KVDBList list
type KVDBList struct {
db.DB
L *db.ListHelper
}
// List 列表
func (l *KVDBList) List(prefix, key []byte, count, direction int32) ([][]byte, error) {
vals := l.L.List(prefix, key, count, direction)
if vals == nil {
return nil, types33.ErrNotFound
}
return vals, nil
}
// PrefixCount 前缀长度
func (l *KVDBList) PrefixCount(prefix []byte) int64 {
return l.L.PrefixCount(prefix)
}
// NewKVDB new
func NewKVDBList(d db.DB) *KVDBList {
return &KVDBList{DB: d, L: db.NewListHelper(d)}
}
func (e *Evmxgo) Initialize(configPath string, ID string, extra []byte) error { func (e *Evmxgo) Initialize(configPath string, ID string, extra []byte) error {
// TODO implement me
// 初始化e.client工作 // 初始化e.client工作
e.eventC = make(chan *pb.IBTP, 10) e.eventC = make(chan *pb.IBTP, 10)
e.done = make(chan bool) e.done = make(chan bool)
...@@ -107,7 +131,22 @@ func (e *Evmxgo) Initialize(configPath string, ID string, extra []byte) error { ...@@ -107,7 +131,22 @@ func (e *Evmxgo) Initialize(configPath string, ID string, extra []byte) error {
return fmt.Errorf("unmarshal config for plugin :%w", err) return fmt.Errorf("unmarshal config for plugin :%w", err)
} }
logger.Info("=========privateKey======", chain33Config.Chain33.PrivateKey) logger.Info("=========privateKey======", chain33Config.Chain33.PrivateKey)
// 初始化chain33 client rpc
url := fmt.Sprintf("http://%s", chain33Config.Chain33.Addr)
client, err := rpc.NewClient("", url)
if err != nil {
return err
}
e.client = client
// 加载高度,从本地磁盘加载。 // 加载高度,从本地磁盘加载。
dbConfig := chain33Config.Chain33.DB
// blockStoreDB := dbm.NewDB("blockchain", "leveldb", dir, 100)
d := db.NewDB(dbConfig.Name, dbConfig.Driver, dbConfig.DbPath, dbConfig.DbCache)
e.db = NewKVDBList(d)
// 启动定时器,检查是否有遗漏的数据。
// 检验已经完成的数据。
return nil return nil
} }
...@@ -156,10 +195,10 @@ func (e *Evmxgo) polling() chan *typess.Event { ...@@ -156,10 +195,10 @@ func (e *Evmxgo) polling() chan *typess.Event {
for i, tx := range item.Block.Txs { for i, tx := range item.Block.Txs {
if tx.Execer == execer { if tx.Execer == execer {
switch item.Receipts[i].Ty { switch item.Receipts[i].Ty {
case types.ExecOk: // OK case util.ExecOk: // OK
if item.Receipts[i].TyName == evmxgotypes.NameMintMapAction { if item.Receipts[i].TyName == evmxgotypes.NameMintMapAction {
var mintEvent evmxgotypes.EvmxgoMintMap var mintEvent evmxgotypes.EvmxgoMintMap
tool.ErrorCheck(types.Decode(tx.Payload, &mintEvent)) tool.ErrorCheck(util.Decode(tx.Payload, &mintEvent))
if len(mintEvent.Extra) > 0 { // 存在关联的数据 if len(mintEvent.Extra) > 0 { // 存在关联的数据
event := &typess.Event{ event := &typess.Event{
TxID: tx.Hash, TxID: tx.Hash,
...@@ -178,12 +217,18 @@ func (e *Evmxgo) polling() chan *typess.Event { ...@@ -178,12 +217,18 @@ func (e *Evmxgo) polling() chan *typess.Event {
Extra: mintEvent.Extra, Extra: mintEvent.Extra,
}, },
} }
// 铸币成功,置换DB中的状态。
// updateLockMint()
// SaveLock
// SaveMint
// saveBurn
ch <- event ch <- event
} }
} }
if item.Receipts[i].TyName == evmxgotypes.NameBurnMapAction { if item.Receipts[i].TyName == evmxgotypes.NameBurnMapAction {
var mintEvent evmxgotypes.EvmxgoBurnMap var mintEvent evmxgotypes.EvmxgoBurnMap
tool.ErrorCheck(types.Decode(tx.Payload, &mintEvent)) tool.ErrorCheck(util.Decode(tx.Payload, &mintEvent))
if len(mintEvent.Extra) > 0 { if len(mintEvent.Extra) > 0 {
// 已销毁 // 已销毁
event := &typess.Event{ event := &typess.Event{
...@@ -210,13 +255,13 @@ func (e *Evmxgo) polling() chan *typess.Event { ...@@ -210,13 +255,13 @@ func (e *Evmxgo) polling() chan *typess.Event {
} }
case types.ExecErr: // Error case util.ExecErr: // Error
logger.Error("transaction error ", logger.Error("transaction error ",
"tx:", tx, "tx:", tx,
"height:", item.Block.Height, "height:", item.Block.Height,
) )
case types.ExecPack: case util.ExecPack:
logger.Error("exec error!", logger.Error("exec error!",
"tx:", tx, "tx:", tx,
"height:", item.Block.Height, "height:", item.Block.Height,
...@@ -238,10 +283,56 @@ func (e *Evmxgo) polling() chan *typess.Event { ...@@ -238,10 +283,56 @@ func (e *Evmxgo) polling() chan *typess.Event {
return ch return ch
} }
func (e *Evmxgo) save(prefix string, event *typess.Event) {
// key: prefix + chainID + blocknumber + txID
key := fmt.Sprintf("%s-%s-%d-%s", prefix, event.Contract.ChainID, event.BlockNumber, event.TxID)
data := util.Encode(event)
_ = e.db.Set([]byte(key), data)
}
// 在联盟链一侧,用户发起销毁:1、销毁部分。2、销毁全部
func (e *Evmxgo) saveBurn(event *typess.Event) {
e.save("burn", event)
}
// 在公链一侧,用户发起铸币。
func (e *Evmxgo) saveLock(event *typess.Event) {
e.save("lock", event)
}
func (e *Evmxgo) saveMint(event *typess.Event) {
e.save("mint", event)
}
// lock => mint => ack lock
func (e *Evmxgo) updateLockMint(event *typess.Event) {
// prefix-src_id-dist_id-
// key := fmt.Sprintf("lockmint-%s-%s")
// e.db.
}
// 保存event: key = txid ; value = event 点查询
// 指定高度的交易: key = prefix + chainID + blocknumber ; value = txid 范围查询
// 未完成绑定的event: key = prefix + "undone" ; value = txID 范围查询
// 已完成绑定的event: key = prefix + "done" ; value = txID + txID 范围查询
// 点查询、范围查询、前缀查询、指定key的一段查询等。
//[start, limit) 范围内的数据:
// 需要完成双向握手
// burn => unlock => ack burn
func (e *Evmxgo) updateBurnUnlock() {
}
// unlock => burn => ack unlock
func (e *Evmxgo) updateUnlockBurn() {
}
func (e *Evmxgo) listenAppChain() { func (e *Evmxgo) listenAppChain() {
ch := e.polling() ch := e.polling()
for event := range ch { for event := range ch {
payload := types.Encode(event) payload := util.Encode(event)
tmp := time.Now().UnixNano() tmp := time.Now().UnixNano()
ibtp := &pb.IBTP{ ibtp := &pb.IBTP{
From: e.appChainID, From: e.appChainID,
...@@ -284,7 +375,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) { ...@@ -284,7 +375,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) {
case pb.IBTP_INTERCHAIN: case pb.IBTP_INTERCHAIN:
// 上链之前,先查询,是否存在 // 上链之前,先查询,是否存在
data := &typess.Event{} data := &typess.Event{}
err := types.Decode(ibtp.Payload, data) err := util.Decode(ibtp.Payload, data)
if err != nil { if err != nil {
logger.Error("decode error", err) logger.Error("decode error", err)
} }
...@@ -293,7 +384,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) { ...@@ -293,7 +384,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) {
// 2、正在执行的交易重复发送。 // 2、正在执行的交易重复发送。
// 3、失败的交易重复发送。 // 3、失败的交易重复发送。
event := &typess.Event{} event := &typess.Event{}
err := types.Decode(data.Payload.Extra, event) err := util.Decode(data.Payload.Extra, event)
if err != nil { if err != nil {
logger.Error("decode error", err) logger.Error("decode error", err)
} }
...@@ -301,7 +392,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) { ...@@ -301,7 +392,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) {
} else { } else {
// 未上链 // 未上链
tx := &types.Transaction{ tx := &types33.Transaction{
Execer: []byte(execer), Execer: []byte(execer),
Fee: 1e5, // TODO Fee: 1e5, // TODO
Nonce: rand.Int63n(time.Now().UnixNano()), Nonce: rand.Int63n(time.Now().UnixNano()),
...@@ -315,7 +406,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) { ...@@ -315,7 +406,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) {
Recipient: data.Payload.LockAddress, Recipient: data.Payload.LockAddress,
Extra: ibtp.Payload, // TODO 附加已经完成的事件 Extra: ibtp.Payload, // TODO 附加已经完成的事件
} }
tx.Payload = types.Encode(mint) tx.Payload = util.Encode(mint)
} else if data.Payload.EventType == typess.EventType_UnLock { } else if data.Payload.EventType == typess.EventType_UnLock {
// 请求与应答 // 请求与应答
...@@ -328,7 +419,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) { ...@@ -328,7 +419,7 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) {
// Amount: data.Payload.MintAmount, // Amount: data.Payload.MintAmount,
// Extra: ibtp.Payload, //TODO 附加已经完成的事件 // Extra: ibtp.Payload, //TODO 附加已经完成的事件
//} //}
//tx.Payload = types.Encode(mint) //tx.Payload = util.Encode(mint)
} }
res, err := e.client.SendTransactionSync(e.pk, tx) res, err := e.client.SendTransactionSync(e.pk, tx)
...@@ -350,6 +441,11 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) { ...@@ -350,6 +441,11 @@ func (e *Evmxgo) SubmitIBTP(ibtp *pb.IBTP) (*pb.SubmitIBTPResponse, error) {
} }
//err := e.db.SetSync()
//if err != nil {
//
//}
// 返回结果是一个状态。并不是回执。需要保证对应的状态。或者请求持久化。 // 返回结果是一个状态。并不是回执。需要保证对应的状态。或者请求持久化。
return ibtpRes, nil return ibtpRes, nil
} }
......
...@@ -5,29 +5,41 @@ go 1.18 ...@@ -5,29 +5,41 @@ go 1.18
replace github.com/33cn/plugin v1.66.3 => /Users/suyanlong/fuzhamei/plugin replace github.com/33cn/plugin v1.66.3 => /Users/suyanlong/fuzhamei/plugin
require ( require (
github.com/33cn/chain33 v1.67.0
github.com/33cn/plugin v1.66.3 github.com/33cn/plugin v1.66.3
github.com/Rican7/retry v0.3.1 github.com/btcsuite/btcd v0.22.0-beta
github.com/bitly/go-simplejson v0.5.0
github.com/cloudflare/cfssl v1.6.1 github.com/cloudflare/cfssl v1.6.1
github.com/golang/protobuf v1.5.2
github.com/hashicorp/go-hclog v1.2.0 github.com/hashicorp/go-hclog v1.2.0
github.com/hashicorp/go-plugin v1.4.3 github.com/hashicorp/go-plugin v1.4.3
github.com/mr-tron/base58 v1.2.0
github.com/spf13/viper v1.10.1 github.com/spf13/viper v1.10.1
gitlab.33.cn/link33/chain33-sdk-go v0.0.0-20211208090718-d6e59899ef37 github.com/stretchr/testify v1.7.0
github.com/tjfoc/gmsm v1.3.2
gitlab.33.cn/link33/sidecar v0.0.0-20220120062340-04eb4a2e720f gitlab.33.cn/link33/sidecar v0.0.0-20220120062340-04eb4a2e720f
go.starlark.net v0.0.0-20220302181546-5411bad688d1 go.starlark.net v0.0.0-20220302181546-5411bad688d1
golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871
google.golang.org/protobuf v1.27.1
) )
require ( require (
github.com/33cn/chain33 v1.67.0 // indirect github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect
github.com/BurntSushi/toml v0.3.1 // indirect github.com/BurntSushi/toml v0.3.1 // indirect
github.com/Rican7/retry v0.3.1 // indirect
github.com/XiaoMi/pegasus-go-client v0.0.0-20210825081735-b8a75c1eac2b // indirect
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de // indirect github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de // indirect
github.com/btcsuite/btcd v0.22.0-beta // indirect
github.com/bxcodec/faker/v3 v3.6.0 // indirect github.com/bxcodec/faker/v3 v3.6.0 // indirect
github.com/cbergoon/merkletree v0.2.0 // indirect github.com/cbergoon/merkletree v0.2.0 // indirect
github.com/cenkalti/backoff/v4 v4.1.1 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/creasty/defaults v1.5.2 // indirect github.com/creasty/defaults v1.5.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/base58 v1.0.3 // indirect github.com/decred/base58 v1.0.3 // indirect
github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect
github.com/ethereum/go-ethereum v1.10.16 // indirect github.com/dgraph-io/badger v1.6.2 // indirect
github.com/dgraph-io/ristretto v0.0.2 // indirect
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/fatih/color v1.13.0 // indirect github.com/fatih/color v1.13.0 // indirect
github.com/fsnotify/fsnotify v1.5.1 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/go-stack/stack v1.8.0 // indirect github.com/go-stack/stack v1.8.0 // indirect
...@@ -36,7 +48,7 @@ require ( ...@@ -36,7 +48,7 @@ require (
github.com/gobuffalo/packr v1.30.1 // indirect github.com/gobuffalo/packr v1.30.1 // indirect
github.com/goccy/go-json v0.7.10 // indirect github.com/goccy/go-json v0.7.10 // indirect
github.com/gogo/protobuf v1.3.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect github.com/golang/snappy v0.0.4 // indirect
github.com/gookit/goutil v0.3.15 // indirect github.com/gookit/goutil v0.3.15 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/errwrap v1.0.0 // indirect
...@@ -46,7 +58,6 @@ require ( ...@@ -46,7 +58,6 @@ require (
github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb // indirect github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb // indirect
github.com/huandu/xstrings v1.3.2 // indirect github.com/huandu/xstrings v1.3.2 // indirect
github.com/imdario/mergo v0.3.12 // indirect github.com/imdario/mergo v0.3.12 // indirect
github.com/inconshreveable/log15 v0.0.0-20201112154412-8562bdadbbac // indirect
github.com/jinzhu/copier v0.3.2 // indirect github.com/jinzhu/copier v0.3.2 // indirect
github.com/jinzhu/now v1.1.2 // indirect github.com/jinzhu/now v1.1.2 // indirect
github.com/joho/godotenv v1.3.0 // indirect github.com/joho/godotenv v1.3.0 // indirect
...@@ -58,29 +69,34 @@ require ( ...@@ -58,29 +69,34 @@ require (
github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.0.0 // indirect github.com/mitchellh/go-testing-interface v1.0.0 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/mr-tron/base58 v1.2.0 // indirect
github.com/oklog/run v1.1.0 // indirect github.com/oklog/run v1.1.0 // indirect
github.com/pegasus-kv/thrift v0.13.0 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect github.com/pelletier/go-toml v1.9.4 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563 // indirect
github.com/rogpeppe/go-internal v1.8.0 // indirect github.com/rogpeppe/go-internal v1.8.0 // indirect
github.com/shopspring/decimal v1.2.0 // indirect github.com/shopspring/decimal v1.2.0 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/spf13/afero v1.6.0 // indirect github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/cast v1.4.1 // indirect github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.2.0 // indirect github.com/subosito/gotenv v1.2.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect
github.com/thoas/go-funk v0.9.1 // indirect github.com/thoas/go-funk v0.9.1 // indirect
github.com/tjfoc/gmsm v1.3.2 // indirect
github.com/vmihailenco/msgpack/v5 v5.3.4 // indirect github.com/vmihailenco/msgpack/v5 v5.3.4 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
golang.org/x/crypto v0.0.0-20211117183948-ae814b36b871 // indirect
golang.org/x/exp v0.0.0-20220317015231-48e79f11773a // indirect
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 // indirect golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 // indirect
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect
golang.org/x/text v0.3.7 // indirect golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.1.8-0.20211029000441-d6a9af8af023 // indirect
google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa // indirect google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa // indirect
google.golang.org/grpc v1.43.0 // indirect google.golang.org/grpc v1.43.0 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/ini.v1 v1.66.2 // indirect gopkg.in/ini.v1 v1.66.2 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
k8s.io/apimachinery v0.17.5 // indirect
) )
This diff is collapsed.
...@@ -3,10 +3,13 @@ package main ...@@ -3,10 +3,13 @@ package main
import ( import (
"fmt" "fmt"
_ "github.com/33cn/chain33/system/store/init"
"github.com/hashicorp/go-plugin" "github.com/hashicorp/go-plugin"
"gitlab.33.cn/link33/sidecar-client-chain33/evmxgo" "gitlab.33.cn/link33/sidecar-client-chain33/evmxgo"
"gitlab.33.cn/link33/sidecar-client-chain33/paracross" "gitlab.33.cn/link33/sidecar-client-chain33/paracross"
"gitlab.33.cn/link33/sidecar/pkg/plugins" "gitlab.33.cn/link33/sidecar/pkg/plugins"
_ "github.com/33cn/chain33/common/db"
) )
func main() { func main() {
......
package util
import (
"encoding/hex"
"io/ioutil"
secp256k1 "github.com/btcsuite/btcd/btcec"
"github.com/golang/protobuf/proto"
)
// exec type
const (
ExecErr = 0
ExecPack = 1
ExecOk = 2
)
// FromHex hex -> []byte
func FromHex(s string) ([]byte, error) {
if len(s) > 1 {
if s[0:2] == "0x" || s[0:2] == "0X" {
s = s[2:]
}
if len(s)%2 == 1 {
s = "0" + s
}
return hex.DecodeString(s)
}
return []byte{}, nil
}
// ToHex []byte -> hex
func ToHex(b []byte) string {
hex := hex.EncodeToString(b)
// Prefer output of "0x0" instead of "0x"
if len(hex) == 0 {
return ""
}
return hex
}
// ToHex []byte -> hex
func ToHexPrefix(b []byte) string {
hex := hex.EncodeToString(b)
// Prefer output of "0x0" instead of "0x"
if len(hex) == 0 {
return ""
}
return "0x" + hex
}
// Encode 编码
func Encode(data proto.Message) []byte {
b, err := proto.Marshal(data)
if err != nil {
panic(err)
}
return b
}
// Decode 解码
func Decode(data []byte, msg proto.Message) error {
return proto.Unmarshal(data, msg)
}
// ECDH Calculate a shared secret using elliptic curve Diffie-Hellman
func ECDH(priv *secp256k1.PrivateKey, pub *secp256k1.PublicKey) []byte {
ecKey := &secp256k1.PublicKey{}
ecKey.X, ecKey.Y = secp256k1.S256().ScalarMult(pub.X, pub.Y, priv.D.Bytes())
return ecKey.SerializeCompressed()
}
func ReadFile(file string) ([]byte, error) {
fileCont, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
return fileCont, nil
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment