Commit 7d479106 authored by duanjinfei's avatar duanjinfei

add moudle dependent

parent fd9bd792
Pipeline #573 canceled with stages
.idea
.vscode
build
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
package main
import (
"crypto/ecdsa"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"math/big"
)
type Account struct {
Address common.Address `json:"address"`
Private string `json:"private"`
Nonce uint64 `json:"nonce"`
PK *ecdsa.PrivateKey `json:"-"`
}
func (acc *Account) MakeInitTx(chainid *big.Int) *types.Transaction {
unit := new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
txData := &types.LegacyTx{
Nonce: 0,
To: &acc.Address,
Value: new(big.Int).Mul(unit, big.NewInt(10)),
Gas: 300000,
GasPrice: big.NewInt(1000000000),
Data: nil,
}
tx, err := acc.SignTx(types.NewTx(txData), chainid)
if err != nil {
return nil
}
return tx
}
func (acc *Account) SignTx(tx *types.Transaction, chainid *big.Int) (*types.Transaction, error){
signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainid), acc.PK)
if err != nil {
return nil, err
}
return signedTx, nil
}
func CreateAccounts(count int) []*Account {
accs := make([]*Account, 0, count)
for i:=0; i < count; i++ {
pk,_ := crypto.GenerateKey()
addr := crypto.PubkeyToAddress(pk.PublicKey)
private := hexutil.Encode(crypto.FromECDSA(pk))
accs = append(accs, &Account{Address: addr, Private: private, PK: pk})
}
return accs
}
# Build MetaCryptor in a stock Go builder container
FROM golang:alpine as builder
RUN apk add --no-cache make git gcc musl-dev linux-headers
ADD . /code
ENV GO111MODULE off
RUN cd /code && make metacryptor
FROM alpine:latest
RUN echo "https://mirror.tuna.tsinghua.edu.cn/alpine/v3.4/main/" > /etc/apk/repositories
RUN apk update \
&& apk upgrade \
&& apk add --no-cache bash \
bash-doc \
bash-completion \
&& rm -rf /var/cache/apk/* \
&& /bin/bash
RUN apk add --no-cache ca-certificates
COPY --from=builder /code/build/bin/metacryptor /usr/local/bin/
EXPOSE 38001
ENTRYPOINT ["metacryptor"]
MIT License
Copyright (c) 2022 CaduceusMetaverseProtocol
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
.PHONY: default metacryptor all clean fmt docker
GOBIN = $(shell pwd)/build/bin
GO ?= latest
GOFILES_NOVENDOR := $(shell go list -f "{{.Dir}}" ./...)
default: metacryptor
all: metacryptor metacryptor-ocl
metacryptor-ocl:
go build -tags opencl -o=${GOBIN}/$@
@echo "Done building."
metacryptor:
go build -o=${GOBIN}/$@
@echo "Done building."
clean:
rm -fr build/*
docker:
docker build -t cmpchain/metacryptor:latest .
# MetaCryptor
MetaCryptor is an independent module in CMPChain that supports the parallel encryption and decrypt which algorithm is ECDSA secp256k1.
package common
import (
metatypes "github.com/CaduceusMetaverseProtocol/MetaTypes/types"
ethcmn "github.com/ethereum/go-ethereum/common"
"math/big"
)
func FromBigInt(b *big.Int) *metatypes.BigInt {
n := metatypes.NewBigInt(0)
if b != nil {
n.Set(b)
}
return n
}
func ToBigInt(b *metatypes.BigInt) *big.Int {
return b.GetInt()
}
func ToHash(d []byte) *metatypes.Hash {
h := new(metatypes.Hash)
h.SetBytes(d)
return h
}
func ToEthAddress(d *metatypes.Address) *ethcmn.Address {
addr := new(ethcmn.Address)
if d != nil {
addr.SetBytes(d.Bytes())
}
return addr
}
func FromEthAddress(e *ethcmn.Address) *metatypes.Address {
addr := new(metatypes.Address)
addr.SetBytes(e.Bytes())
return addr
}
package common
import (
"encoding/hex"
"errors"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/hexutil"
)
// FromHex returns the bytes represented by the hexadecimal string s.
// s may be prefixed with "0x".
func FromHex(s string) []byte {
if has0xPrefix(s) {
s = s[2:]
}
if len(s)%2 == 1 {
s = "0" + s
}
return Hex2Bytes(s)
}
// CopyBytes returns an exact copy of the provided bytes.
func CopyBytes(b []byte) (copiedBytes []byte) {
if b == nil {
return nil
}
copiedBytes = make([]byte, len(b))
copy(copiedBytes, b)
return
}
// has0xPrefix validates str begins with '0x' or '0X'.
func has0xPrefix(str string) bool {
return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
}
// isHexCharacter returns bool of c being a valid hexadecimal.
func isHexCharacter(c byte) bool {
return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
}
// isHex validates whether each byte is valid hexadecimal string.
func isHex(str string) bool {
if len(str)%2 != 0 {
return false
}
for _, c := range []byte(str) {
if !isHexCharacter(c) {
return false
}
}
return true
}
// Bytes2Hex returns the hexadecimal encoding of d.
func Bytes2Hex(d []byte) string {
return hex.EncodeToString(d)
}
// Hex2Bytes returns the bytes represented by the hexadecimal string str.
func Hex2Bytes(str string) []byte {
h, _ := hex.DecodeString(str)
return h
}
// Hex2BytesFixed returns bytes of a specified fixed length flen.
func Hex2BytesFixed(str string, flen int) []byte {
h, _ := hex.DecodeString(str)
if len(h) == flen {
return h
}
if len(h) > flen {
return h[len(h)-flen:]
}
hh := make([]byte, flen)
copy(hh[flen-len(h):flen], h)
return hh
}
// ParseHexOrString tries to hexdecode b, but if the prefix is missing, it instead just returns the raw bytes
func ParseHexOrString(str string) ([]byte, error) {
b, err := hexutil.Decode(str)
if errors.Is(err, hexutil.ErrMissingPrefix) {
return []byte(str), nil
}
return b, err
}
// RightPadBytes zero-pads slice to the right up to length l.
func RightPadBytes(slice []byte, l int) []byte {
if l <= len(slice) {
return slice
}
padded := make([]byte, l)
copy(padded, slice)
return padded
}
// LeftPadBytes zero-pads slice to the left up to length l.
func LeftPadBytes(slice []byte, l int) []byte {
if l <= len(slice) {
return slice
}
padded := make([]byte, l)
copy(padded[l-len(slice):], slice)
return padded
}
// TrimLeftZeroes returns a subslice of s without leading zeroes
func TrimLeftZeroes(s []byte) []byte {
idx := 0
for ; idx < len(s); idx++ {
if s[idx] != 0 {
break
}
}
return s[idx:]
}
// TrimRightZeroes returns a subslice of s without trailing zeroes
func TrimRightZeroes(s []byte) []byte {
idx := len(s)
for ; idx > 0; idx-- {
if s[idx-1] != 0 {
break
}
}
return s[:idx]
}
package hexutil
import (
"encoding/hex"
"fmt"
"math/big"
"strconv"
)
const uintBits = 32 << (uint64(^uint(0)) >> 63)
// Errors
var (
ErrEmptyString = &decError{"empty hex string"}
ErrSyntax = &decError{"invalid hex string"}
ErrMissingPrefix = &decError{"hex string without 0x prefix"}
ErrOddLength = &decError{"hex string of odd length"}
ErrEmptyNumber = &decError{"hex string \"0x\""}
ErrLeadingZero = &decError{"hex number with leading zero digits"}
ErrUint64Range = &decError{"hex number > 64 bits"}
ErrUintRange = &decError{fmt.Sprintf("hex number > %d bits", uintBits)}
ErrBig256Range = &decError{"hex number > 256 bits"}
)
type decError struct{ msg string }
func (err decError) Error() string { return err.msg }
// Decode decodes a hex string with 0x prefix.
func Decode(input string) ([]byte, error) {
if len(input) == 0 {
return nil, ErrEmptyString
}
if !has0xPrefix(input) {
return nil, ErrMissingPrefix
}
b, err := hex.DecodeString(input[2:])
if err != nil {
err = mapError(err)
}
return b, err
}
// MustDecode decodes a hex string with 0x prefix. It panics for invalid input.
func MustDecode(input string) []byte {
dec, err := Decode(input)
if err != nil {
panic(err)
}
return dec
}
// Encode encodes b as a hex string with 0x prefix.
func Encode(b []byte) string {
enc := make([]byte, len(b)*2+2)
copy(enc, "0x")
hex.Encode(enc[2:], b)
return string(enc)
}
// DecodeUint64 decodes a hex string with 0x prefix as a quantity.
func DecodeUint64(input string) (uint64, error) {
raw, err := checkNumber(input)
if err != nil {
return 0, err
}
dec, err := strconv.ParseUint(raw, 16, 64)
if err != nil {
err = mapError(err)
}
return dec, err
}
// MustDecodeUint64 decodes a hex string with 0x prefix as a quantity.
// It panics for invalid input.
func MustDecodeUint64(input string) uint64 {
dec, err := DecodeUint64(input)
if err != nil {
panic(err)
}
return dec
}
// EncodeUint64 encodes i as a hex string with 0x prefix.
func EncodeUint64(i uint64) string {
enc := make([]byte, 2, 10)
copy(enc, "0x")
return string(strconv.AppendUint(enc, i, 16))
}
var bigWordNibbles int
func init() {
// This is a weird way to compute the number of nibbles required for big.Word.
// The usual way would be to use constant arithmetic but go vet can't handle that.
b, _ := new(big.Int).SetString("FFFFFFFFFF", 16)
switch len(b.Bits()) {
case 1:
bigWordNibbles = 16
case 2:
bigWordNibbles = 8
default:
panic("weird big.Word size")
}
}
// DecodeBig decodes a hex string with 0x prefix as a quantity.
// Numbers larger than 256 bits are not accepted.
func DecodeBig(input string) (*big.Int, error) {
raw, err := checkNumber(input)
if err != nil {
return nil, err
}
if len(raw) > 64 {
return nil, ErrBig256Range
}
words := make([]big.Word, len(raw)/bigWordNibbles+1)
end := len(raw)
for i := range words {
start := end - bigWordNibbles
if start < 0 {
start = 0
}
for ri := start; ri < end; ri++ {
nib := decodeNibble(raw[ri])
if nib == badNibble {
return nil, ErrSyntax
}
words[i] *= 16
words[i] += big.Word(nib)
}
end = start
}
dec := new(big.Int).SetBits(words)
return dec, nil
}
// MustDecodeBig decodes a hex string with 0x prefix as a quantity.
// It panics for invalid input.
func MustDecodeBig(input string) *big.Int {
dec, err := DecodeBig(input)
if err != nil {
panic(err)
}
return dec
}
// EncodeBig encodes bigint as a hex string with 0x prefix.
func EncodeBig(bigint *big.Int) string {
if sign := bigint.Sign(); sign == 0 {
return "0x0"
} else if sign > 0 {
return "0x" + bigint.Text(16)
} else {
return "-0x" + bigint.Text(16)[1:]
}
}
func has0xPrefix(input string) bool {
return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X')
}
func checkNumber(input string) (raw string, err error) {
if len(input) == 0 {
return "", ErrEmptyString
}
if !has0xPrefix(input) {
return "", ErrMissingPrefix
}
input = input[2:]
if len(input) == 0 {
return "", ErrEmptyNumber
}
if len(input) > 1 && input[0] == '0' {
return "", ErrLeadingZero
}
return input, nil
}
const badNibble = ^uint64(0)
func decodeNibble(in byte) uint64 {
switch {
case in >= '0' && in <= '9':
return uint64(in - '0')
case in >= 'A' && in <= 'F':
return uint64(in - 'A' + 10)
case in >= 'a' && in <= 'f':
return uint64(in - 'a' + 10)
default:
return badNibble
}
}
func mapError(err error) error {
if err, ok := err.(*strconv.NumError); ok {
switch err.Err {
case strconv.ErrRange:
return ErrUint64Range
case strconv.ErrSyntax:
return ErrSyntax
}
}
if _, ok := err.(hex.InvalidByteError); ok {
return ErrSyntax
}
if err == hex.ErrLength {
return ErrOddLength
}
return err
}
package hexutil
import (
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"reflect"
"strconv"
)
var (
bytesT = reflect.TypeOf(Bytes(nil))
bigT = reflect.TypeOf((*Big)(nil))
uintT = reflect.TypeOf(Uint(0))
uint64T = reflect.TypeOf(Uint64(0))
)
// Bytes marshals/unmarshals as a JSON string with 0x prefix.
// The empty slice marshals as "0x".
type Bytes []byte
// MarshalText implements encoding.TextMarshaler
func (b Bytes) MarshalText() ([]byte, error) {
result := make([]byte, len(b)*2+2)
copy(result, `0x`)
hex.Encode(result[2:], b)
return result, nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (b *Bytes) UnmarshalJSON(input []byte) error {
if !isString(input) {
return errNonString(bytesT)
}
return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bytesT)
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (b *Bytes) UnmarshalText(input []byte) error {
raw, err := checkText(input, true)
if err != nil {
return err
}
dec := make([]byte, len(raw)/2)
if _, err = hex.Decode(dec, raw); err != nil {
err = mapError(err)
} else {
*b = dec
}
return err
}
// String returns the hex encoding of b.
func (b Bytes) String() string {
return Encode(b)
}
// ImplementsGraphQLType returns true if Bytes implements the specified GraphQL type.
func (b Bytes) ImplementsGraphQLType(name string) bool { return name == "Bytes" }
// UnmarshalGraphQL unmarshals the provided GraphQL query data.
func (b *Bytes) UnmarshalGraphQL(input interface{}) error {
var err error
switch input := input.(type) {
case string:
data, err := Decode(input)
if err != nil {
return err
}
*b = data
default:
err = fmt.Errorf("unexpected type %T for Bytes", input)
}
return err
}
// UnmarshalFixedJSON decodes the input as a string with 0x prefix. The length of out
// determines the required input length. This function is commonly used to implement the
// UnmarshalJSON method for fixed-size types.
func UnmarshalFixedJSON(typ reflect.Type, input, out []byte) error {
if !isString(input) {
return errNonString(typ)
}
return wrapTypeError(UnmarshalFixedText(typ.String(), input[1:len(input)-1], out), typ)
}
// UnmarshalFixedText decodes the input as a string with 0x prefix. The length of out
// determines the required input length. This function is commonly used to implement the
// UnmarshalText method for fixed-size types.
func UnmarshalFixedText(typname string, input, out []byte) error {
raw, err := checkText(input, true)
if err != nil {
return err
}
if len(raw)/2 != len(out) {
return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname)
}
// Pre-verify syntax before modifying out.
for _, b := range raw {
if decodeNibble(b) == badNibble {
return ErrSyntax
}
}
hex.Decode(out, raw)
return nil
}
// UnmarshalFixedUnprefixedText decodes the input as a string with optional 0x prefix. The
// length of out determines the required input length. This function is commonly used to
// implement the UnmarshalText method for fixed-size types.
func UnmarshalFixedUnprefixedText(typname string, input, out []byte) error {
raw, err := checkText(input, false)
if err != nil {
return err
}
if len(raw)/2 != len(out) {
return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname)
}
// Pre-verify syntax before modifying out.
for _, b := range raw {
if decodeNibble(b) == badNibble {
return ErrSyntax
}
}
hex.Decode(out, raw)
return nil
}
// Big marshals/unmarshals as a JSON string with 0x prefix.
// The zero value marshals as "0x0".
//
// Negative integers are not supported at this time. Attempting to marshal them will
// return an error. Values larger than 256bits are rejected by Unmarshal but will be
// marshaled without error.
type Big big.Int
// MarshalText implements encoding.TextMarshaler
func (b Big) MarshalText() ([]byte, error) {
return []byte(EncodeBig((*big.Int)(&b))), nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (b *Big) UnmarshalJSON(input []byte) error {
if !isString(input) {
return errNonString(bigT)
}
return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bigT)
}
// UnmarshalText implements encoding.TextUnmarshaler
func (b *Big) UnmarshalText(input []byte) error {
raw, err := checkNumberText(input)
if err != nil {
return err
}
if len(raw) > 64 {
return ErrBig256Range
}
words := make([]big.Word, len(raw)/bigWordNibbles+1)
end := len(raw)
for i := range words {
start := end - bigWordNibbles
if start < 0 {
start = 0
}
for ri := start; ri < end; ri++ {
nib := decodeNibble(raw[ri])
if nib == badNibble {
return ErrSyntax
}
words[i] *= 16
words[i] += big.Word(nib)
}
end = start
}
var dec big.Int
dec.SetBits(words)
*b = (Big)(dec)
return nil
}
// ToInt converts b to a big.Int.
func (b *Big) ToInt() *big.Int {
return (*big.Int)(b)
}
// String returns the hex encoding of b.
func (b *Big) String() string {
return EncodeBig(b.ToInt())
}
// ImplementsGraphQLType returns true if Big implements the provided GraphQL type.
func (b Big) ImplementsGraphQLType(name string) bool { return name == "BigInt" }
// UnmarshalGraphQL unmarshals the provided GraphQL query data.
func (b *Big) UnmarshalGraphQL(input interface{}) error {
var err error
switch input := input.(type) {
case string:
return b.UnmarshalText([]byte(input))
case int32:
var num big.Int
num.SetInt64(int64(input))
*b = Big(num)
default:
err = fmt.Errorf("unexpected type %T for BigInt", input)
}
return err
}
// Uint64 marshals/unmarshals as a JSON string with 0x prefix.
// The zero value marshals as "0x0".
type Uint64 uint64
// MarshalText implements encoding.TextMarshaler.
func (b Uint64) MarshalText() ([]byte, error) {
buf := make([]byte, 2, 10)
copy(buf, `0x`)
buf = strconv.AppendUint(buf, uint64(b), 16)
return buf, nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (b *Uint64) UnmarshalJSON(input []byte) error {
if !isString(input) {
return errNonString(uint64T)
}
return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uint64T)
}
// UnmarshalText implements encoding.TextUnmarshaler
func (b *Uint64) UnmarshalText(input []byte) error {
raw, err := checkNumberText(input)
if err != nil {
return err
}
if len(raw) > 16 {
return ErrUint64Range
}
var dec uint64
for _, byte := range raw {
nib := decodeNibble(byte)
if nib == badNibble {
return ErrSyntax
}
dec *= 16
dec += nib
}
*b = Uint64(dec)
return nil
}
// String returns the hex encoding of b.
func (b Uint64) String() string {
return EncodeUint64(uint64(b))
}
// ImplementsGraphQLType returns true if Uint64 implements the provided GraphQL type.
func (b Uint64) ImplementsGraphQLType(name string) bool { return name == "Long" }
// UnmarshalGraphQL unmarshals the provided GraphQL query data.
func (b *Uint64) UnmarshalGraphQL(input interface{}) error {
var err error
switch input := input.(type) {
case string:
return b.UnmarshalText([]byte(input))
case int32:
*b = Uint64(input)
default:
err = fmt.Errorf("unexpected type %T for Long", input)
}
return err
}
// Uint marshals/unmarshals as a JSON string with 0x prefix.
// The zero value marshals as "0x0".
type Uint uint
// MarshalText implements encoding.TextMarshaler.
func (b Uint) MarshalText() ([]byte, error) {
return Uint64(b).MarshalText()
}
// UnmarshalJSON implements json.Unmarshaler.
func (b *Uint) UnmarshalJSON(input []byte) error {
if !isString(input) {
return errNonString(uintT)
}
return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uintT)
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (b *Uint) UnmarshalText(input []byte) error {
var u64 Uint64
err := u64.UnmarshalText(input)
if u64 > Uint64(^uint(0)) || err == ErrUint64Range {
return ErrUintRange
} else if err != nil {
return err
}
*b = Uint(u64)
return nil
}
// String returns the hex encoding of b.
func (b Uint) String() string {
return EncodeUint64(uint64(b))
}
func isString(input []byte) bool {
return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"'
}
func bytesHave0xPrefix(input []byte) bool {
return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X')
}
func checkText(input []byte, wantPrefix bool) ([]byte, error) {
if len(input) == 0 {
return nil, nil // empty strings are allowed
}
if bytesHave0xPrefix(input) {
input = input[2:]
} else if wantPrefix {
return nil, ErrMissingPrefix
}
if len(input)%2 != 0 {
return nil, ErrOddLength
}
return input, nil
}
func checkNumberText(input []byte) (raw []byte, err error) {
if len(input) == 0 {
return nil, nil // empty strings are allowed
}
if !bytesHave0xPrefix(input) {
return nil, ErrMissingPrefix
}
input = input[2:]
if len(input) == 0 {
return nil, ErrEmptyNumber
}
if len(input) > 1 && input[0] == '0' {
return nil, ErrLeadingZero
}
return input, nil
}
func wrapTypeError(err error, typ reflect.Type) error {
if _, ok := err.(*decError); ok {
return &json.UnmarshalTypeError{Value: err.Error(), Type: typ}
}
return err
}
func errNonString(typ reflect.Type) error {
return &json.UnmarshalTypeError{Value: "non-string", Type: typ}
}
package log
import (
"context"
"github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"os"
"path"
"time"
)
var (
mlog = logrus.New()
)
type LogConfig struct {
Save uint `json:"save"`
Path string `json:"path"`
Level string `json:"level"`
}
func InitLog(logConfig LogConfig) {
mlog.Out = os.Stdout
var loglevel logrus.Level
err := loglevel.UnmarshalText([]byte(logConfig.Level))
if err != nil {
mlog.Panicf("set log level failed: %v", err)
}
mlog.SetLevel(loglevel)
mlog.Formatter = &logrus.TextFormatter{FullTimestamp: true, TimestampFormat: "2006-01-2 15:04:05.000"}
localFilesystemLogger(mlog, logConfig.Path, logConfig.Save)
}
func logWriter(logPath string, level string, save uint) *rotatelogs.RotateLogs {
logFullPath := path.Join(logPath, level)
logwriter, err := rotatelogs.New(
logFullPath+".%Y%m%d",
rotatelogs.WithLinkName(logFullPath),
rotatelogs.WithRotationCount(save),
rotatelogs.WithRotationTime(24*time.Hour),
)
if err != nil {
panic(err)
}
return logwriter
}
func localFilesystemLogger(log *logrus.Logger, logPath string, save uint) {
lfHook := lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: logWriter(logPath, "debug", save), // 为不同级别设置不同的输出目的
logrus.InfoLevel: logWriter(logPath, "info", save),
logrus.WarnLevel: logWriter(logPath, "warn", save),
logrus.ErrorLevel: logWriter(logPath, "error", save),
logrus.FatalLevel: logWriter(logPath, "fatal", save),
logrus.PanicLevel: logWriter(logPath, "panic", save),
}, &logrus.TextFormatter{FullTimestamp: true, TimestampFormat: "2006-01-2 15:04:05.000"})
log.AddHook(lfHook)
}
// WithField allocates a new entry and adds a field to it.
// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to
// this new returned entry.
// If you want multiple fields, use `WithFields`.
func WithField(key string, value interface{}) *logrus.Entry {
return mlog.WithField(key, value)
}
// Adds a struct of fields to the log entry. All it does is call `WithField` for
// each `Field`.
func WithFields(fields logrus.Fields) *logrus.Entry {
return mlog.WithFields(fields)
}
// Add an error as single field to the log entry. All it does is call
// `WithError` for the given `error`.
func WithError(err error) *logrus.Entry {
return mlog.WithError(err)
}
// Add a context to the log entry.
func WithContext(ctx context.Context) *logrus.Entry {
return mlog.WithContext(ctx)
}
// Overrides the time of the log entry.
func WithTime(t time.Time) *logrus.Entry {
return mlog.WithTime(t)
}
func Logf(level logrus.Level, format string, args ...interface{}) {
mlog.Logf(level, format, args...)
}
func Tracef(format string, args ...interface{}) {
mlog.Tracef(format, args...)
}
func Debugf(format string, args ...interface{}) {
mlog.Debugf(format, args...)
}
func Infof(format string, args ...interface{}) {
mlog.Infof(format, args...)
}
func Printf(format string, args ...interface{}) {
mlog.Printf(format, args...)
}
func Warnf(format string, args ...interface{}) {
mlog.Warnf(format, args...)
}
func Warningf(format string, args ...interface{}) {
mlog.Warningf(format, args...)
}
func Errorf(format string, args ...interface{}) {
mlog.Errorf(format, args)
}
func Fatalf(format string, args ...interface{}) {
mlog.Fatalf(format, args...)
}
func Panicf(format string, args ...interface{}) {
mlog.Panicf(format, args...)
}
func Log(level logrus.Level, args ...interface{}) {
mlog.Log(level, args...)
}
func LogFn(level logrus.Level, fn logrus.LogFunction) {
mlog.LogFn(level, fn)
}
func Trace(args ...interface{}) {
mlog.Trace(args...)
}
func Debug(args ...interface{}) {
mlog.Debug(args...)
}
func Info(args ...interface{}) {
mlog.Info(args...)
}
func Print(args ...interface{}) {
mlog.Print(args...)
}
func Warn(args ...interface{}) {
mlog.Warn(args...)
}
func Warning(args ...interface{}) {
mlog.Warning(args...)
}
func Error(args ...interface{}) {
mlog.Error(args...)
}
func Fatal(args ...interface{}) {
mlog.Fatal(args...)
}
func Panic(args ...interface{}) {
mlog.Panic(args...)
}
func TraceFn(fn logrus.LogFunction) {
mlog.TraceFn(fn)
}
func DebugFn(fn logrus.LogFunction) {
mlog.DebugFn(fn)
}
func InfoFn(fn logrus.LogFunction) {
mlog.InfoFn(fn)
}
func PrintFn(fn logrus.LogFunction) {
mlog.PrintFn(fn)
}
func WarnFn(fn logrus.LogFunction) {
mlog.WarnFn(fn)
}
func WarningFn(fn logrus.LogFunction) {
mlog.WarningFn(fn)
}
func ErrorFn(fn logrus.LogFunction) {
mlog.ErrorFn(fn)
}
func FatalFn(fn logrus.LogFunction) {
mlog.FatalFn(fn)
}
func PanicFn(fn logrus.LogFunction) {
mlog.PanicFn(fn)
}
func Logln(level logrus.Level, args ...interface{}) {
mlog.Logln(level, args...)
}
func Traceln(args ...interface{}) {
mlog.Traceln(args...)
}
func Debugln(args ...interface{}) {
mlog.Debugln(args...)
}
func Infoln(args ...interface{}) {
mlog.Infoln(args...)
}
func Println(args ...interface{}) {
mlog.Println(args...)
}
func Warnln(args ...interface{}) {
mlog.Warnln(args...)
}
func Warningln(args ...interface{}) {
mlog.Warningln(args...)
}
func Errorln(args ...interface{}) {
mlog.Errorln(args...)
}
func Fatalln(args ...interface{}) {
mlog.Fatalln(args...)
}
func Panicln(args ...interface{}) {
mlog.Panicln(args...)
}
package crypto
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"github.com/btcsuite/btcd/btcec"
"github.com/ethereum/go-ethereum/crypto"
"github.com/tjfoc/gmsm/sm2"
"math/big"
)
//
func RecoverPubkey(msg, signature []byte) ([]byte, error) {
return crypto.Ecrecover(msg, signature)
}
func RecoverableSign(msg, seckey []byte) ([]byte, error) {
if len(msg) != 32 {
return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(msg))
}
prv, _ := btcec.PrivKeyFromBytes(btcec.S256(), seckey)
sig, err := btcec.SignCompact(btcec.S256(), (*btcec.PrivateKey)(prv), msg, false)
if err != nil {
return nil, err
}
// Convert to Ethereum signature format with 'recovery id' v at the end.
v := sig[0] - 27
copy(sig, sig[1:])
sig[64] = v
return sig, nil
}
func Secp256k1Sign(msg, seckey []byte) ([]byte, error) {
priv, _ := btcec.PrivKeyFromBytes(btcec.S256(), seckey)
msghash := sha256.Sum256(msg)
sig, err := priv.Sign(msghash[:])
if err != nil {
return nil, err
}
rBytes := sig.R.Bytes()
sBytes := sig.S.Bytes()
sigBytes := make([]byte, 64)
// 0 pad the byte arrays from the left if they aren't big enough.
copy(sigBytes[32-len(rBytes):32], rBytes)
copy(sigBytes[64-len(sBytes):64], sBytes)
return sigBytes, nil
}
// warning: pubkey size is 64, not 65.
func Secp256k1Verify(msg, pubkey, sign []byte) (bool, error) {
var secp256k1halfN = new(big.Int).Rsh(btcec.S256().N, 1)
sig := &btcec.Signature{R: new(big.Int).SetBytes(sign[:32]), S: new(big.Int).SetBytes(sign[32:])}
key, err := btcec.ParsePubKey(pubkey, btcec.S256())
if err != nil {
return false, errors.New(fmt.Sprintf("parse to secp256k1 pubkey invalid pubkey:%s", err.Error()))
}
// Reject malleable signatures. libsecp256k1 does this check but btcec doesn't.
if sig.S.Cmp(secp256k1halfN) > 0 {
return false, nil
}
return sig.Verify(msg, key), nil
}
func parseToEcdsaP256PrivateKey(seckey []byte) (*ecdsa.PrivateKey, error) {
if len(seckey) != 32 {
return nil, errors.New("invalid seckey")
}
k := big.NewInt(0).SetBytes(seckey)
p256 := elliptic.P256()
priv := new(ecdsa.PrivateKey)
priv.PublicKey.Curve = p256
priv.D = k
priv.PublicKey.X, priv.PublicKey.Y = p256.ScalarBaseMult(k.Bytes())
return priv, nil
}
func parseToEcdsaP256PublicKey(pubkey []byte) (*ecdsa.PublicKey, error) {
if len(pubkey) != 64 {
return nil, errors.New("parse to ecdsap256 pubkey invalid pubkey")
}
pubk := new(ecdsa.PublicKey)
pubk.Curve = elliptic.P256()
pubk.X = big.NewInt(0).SetBytes(pubkey[:32])
pubk.Y = big.NewInt(0).SetBytes(pubkey[32:64])
return pubk, nil
}
func EcdsaP256Sign(msg, seckey []byte) ([]byte, error) {
privk, err := parseToEcdsaP256PrivateKey(seckey)
if err != nil {
return nil, err
}
// warning: ecdsa sign add random before msg
signature, err := privk.Sign(rand.Reader, msg, nil)
if err != nil {
return nil, err
}
r, s, err := sm2.SignDataToSignDigit(signature)
if err != nil {
return nil, err
}
sign := make([]byte, 64)
copy(sign[:32], r.Bytes())
copy(sign[32:], s.Bytes())
return sign, nil
}
func EcdsaP256Verify(msg []byte, pubkey []byte, sign []byte) (bool, error) {
public, err := parseToEcdsaP256PublicKey(pubkey)
if err != nil {
return false, err
}
r := big.NewInt(0).SetBytes(sign[:32])
s := big.NewInt(0).SetBytes(sign[32:64])
ret := ecdsa.Verify(public, msg, r, s)
return ret, nil
}
func parseToSM2PrivateKey(seckey []byte) (*sm2.PrivateKey, error) {
if len(seckey) != 32 {
return nil, errors.New("invalid seckey")
}
c := sm2.P256Sm2()
k := big.NewInt(0).SetBytes(seckey)
priv := new(sm2.PrivateKey)
priv.PublicKey.Curve = c
priv.D = k
priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
return priv, nil
}
func parseToSM2PublicKey(pubkey []byte) (*sm2.PublicKey, error) {
if len(pubkey) != 64 {
return nil, errors.New("parse to sm2 pubkey and invalid pubkey")
}
c := sm2.P256Sm2()
pubk := new(sm2.PublicKey)
pubk.Curve = c
pubk.X = big.NewInt(0).SetBytes(pubkey[:32])
pubk.Y = big.NewInt(0).SetBytes(pubkey[32:64])
return pubk, nil
}
func SM2Sign(msg, seckey []byte) ([]byte, error) {
priv, err := parseToSM2PrivateKey(seckey)
if err != nil {
return nil, err
}
signature, err := priv.Sign(nil, msg, nil)
if err != nil {
return nil, err
}
r, s, err := sm2.SignDataToSignDigit(signature)
if err != nil {
return nil, err
}
sign := make([]byte, 64)
copy(sign[:32], r.Bytes())
copy(sign[32:], s.Bytes())
return sign, nil
}
func SM2Verify(msg []byte, pubkey []byte, sign []byte) (bool, error) {
public, err := parseToSM2PublicKey(pubkey)
if err != nil {
return false, err
}
r := big.NewInt(0).SetBytes(sign[:32])
s := big.NewInt(0).SetBytes(sign[32:64])
signature, err := sm2.SignDigitToSignData(r, s)
if err != nil {
return false, err
}
ret := public.Verify(msg, signature)
return ret, nil
}
package crypto
import "bytes"
func BytesCombine(pBytes ...[]byte) []byte {
return bytes.Join(pBytes, []byte(""))
}
package crypto
import (
"golang.org/x/crypto/sha3"
"hash"
)
type KeccakState interface {
hash.Hash
Read([]byte) (int, error)
}
// NewKeccakState creates a new KeccakState
func NewKeccakState() KeccakState {
return sha3.NewLegacyKeccak256().(KeccakState)
}
// Keccak256 calculates and returns the Keccak256 hash of the input data.
func Keccak256(data ...[]byte) []byte {
b := make([]byte, 32)
d := NewKeccakState()
for _, b := range data {
d.Write(b)
}
d.Read(b)
return b
}
package crypto
import (
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common"
basev1 "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
"github.com/ethereum/go-ethereum/core/types"
"math/big"
)
func SignedHash(tx *basev1.MetaTxBase, chainid *big.Int) []byte {
txdata := &types.LegacyTx{
Nonce: tx.Nonce,
GasPrice: common.ToBigInt(tx.GasPrice),
Gas: tx.Gas,
To: common.ToEthAddress(tx.To),
Value: common.ToBigInt(tx.Value),
Data: tx.Data,
V: common.ToBigInt(tx.V),
R: common.ToBigInt(tx.R),
S: common.ToBigInt(tx.S),
}
ntx := types.NewTx(txdata)
signer := types.NewEIP155Signer(chainid)
return signer.Hash(ntx).Bytes()
}
module github.com/CaduceusMetaverseProtocol/MetaCryptor
go 1.18
require (
github.com/CaduceusMetaverseProtocol/MetaProtocol v0.0.1
github.com/btcsuite/btcd v0.21.0-beta
github.com/ethereum/go-ethereum v1.10.26
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/rakyll/statik v0.1.7
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/sirupsen/logrus v1.9.0
github.com/tjfoc/gmsm v1.4.1
golang.org/x/crypto v0.5.0
google.golang.org/grpc v1.51.0
)
require (
github.com/CaduceusMetaverseProtocol/MetaTypes v1.0.0 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.2.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/jonboulle/clockwork v0.3.0 // indirect
github.com/lestrrat-go/strftime v1.0.6 // indirect
github.com/pkg/errors v0.9.1 // indirect
golang.org/x/net v0.5.0 // indirect
golang.org/x/sys v0.4.0 // indirect
golang.org/x/text v0.6.0 // indirect
google.golang.org/genproto v0.0.0-20221205194025-8222ab48f5fc // indirect
google.golang.org/protobuf v1.28.1 // indirect
)
replace github.com/CaduceusMetaverseProtocol/MetaProtocol => ../MetaProtocol-main
replace github.com/CaduceusMetaverseProtocol/MetaTypes => ../MetaTypes-main
This diff is collapsed.
package main
import (
"context"
"fmt"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/service"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc"
basetype "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/base/v1"
metacrypter "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/crypter/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"math/big"
"net"
"time"
)
func test() {
time.Sleep(time.Second * 4)
client, err := grpc.Dial("127.0.0.1:38001", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Error("dial server failed", err)
}
accounts := CreateAccounts(1)
log.Info("account address is ", accounts[0].Address.String())
tx := accounts[0].MakeInitTx(big.NewInt(100))
crypterclient := metacrypter.NewCrypterServiceClient(client)
req := new(metacrypter.BatchRecoverTxRequest)
req.RawTx = make([]*basetype.MetaTxBase, 0)
v, r, s := tx.RawSignatureValues()
log.WithField("txhash", tx.Hash().String()).Info("txhash")
log.WithField("r", common.Bytes2Hex(r.Bytes())).Info("tx r")
log.WithField("s", common.Bytes2Hex(s.Bytes())).Info("tx s")
log.WithField("v", common.Bytes2Hex(v.Bytes())).Info("tx v")
rtx := &basetype.MetaTxBase{
TxHash: common.ToHash(tx.Hash().Bytes()),
TxType: 1,
ChainId: common.FromBigInt(big.NewInt(100)),
Gas: tx.Gas(),
GasPrice: common.FromBigInt(tx.GasPrice()),
Value: common.FromBigInt(tx.Value()),
Data: tx.Data(),
Nonce: tx.Nonce(),
To: common.FromEthAddress(tx.To()),
R: common.FromBigInt(r),
S: common.FromBigInt(s),
V: common.FromBigInt(v),
}
req.RawTx = append(req.RawTx, rtx)
res, err := crypterclient.BatchRecoverTx(context.Background(), req, grpc.EmptyCallOption{})
if err != nil {
log.Error("batch recover tx failed", err)
}
log.Info("recover got from ", res.RecoverdTx[0].From)
}
func main() {
xecc.XeccInstance()
lis, err := net.Listen("tcp", ":38001")
if err != nil {
fmt.Printf("failed to listen: %v", err)
return
}
s := grpc.NewServer()
service.RegisterCrypter(s)
go test()
err = s.Serve(lis)
if err != nil {
fmt.Printf("failed to serve: %v", err)
return
}
}
package service
import (
"context"
"encoding/hex"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
metatypes "github.com/CaduceusMetaverseProtocol/MetaTypes/types"
"math/big"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/crypto"
metacrypter "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/crypter/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type CrypterServer struct {
metacrypter.UnimplementedCrypterServiceServer
}
func (*CrypterServer) BatchSign(ctx context.Context, req *metacrypter.BatchSignRequest) (*metacrypter.BatchSignResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchSign not implemented")
}
func (*CrypterServer) BatchVerify(ctx context.Context, req *metacrypter.BatchVerifyRequest) (*metacrypter.BatchVerifyResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchVerify not implemented")
}
func (*CrypterServer) BatchRecover(ctx context.Context, req *metacrypter.BatchRecoverRequest) (*metacrypter.BatchRecoverResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchRecover not implemented")
}
func (*CrypterServer) BatchRecoverTx(ctx context.Context, req *metacrypter.BatchRecoverTxRequest) (*metacrypter.BatchRecoverTxResponse, error) {
//tasks := make([]*XTaskSecp256k1RPubkey, len(req.RawTx))
//big8 := big.NewInt(8)
log.Info("server get batch recover tx request")
froms := make([][]byte, len(req.RawTx))
for i, tx := range req.RawTx {
log.WithField("txhash", tx.TxHash.String()).Info("txhash")
log.WithField("r", tx.R.String()).Info("tx r")
log.WithField("s", tx.S.String()).Info("tx s")
log.WithField("v", tx.V.String()).Info("tx v")
log.WithField("chainid", tx.ChainId.String()).Info("tx chainid")
V := common.ToBigInt(tx.V)
chainid := common.ToBigInt(tx.ChainId)
chainIdMul := new(big.Int).Mul(chainid, big.NewInt(2))
v := new(big.Int).Sub(V, chainIdMul)
vb := byte(v.Uint64() - 35)
log.WithField("vb is ", vb).Info("vb")
signature := make([]byte, 65)
copy(signature[:32], common.LeftPadBytes(tx.R.Bytes(), 32))
copy(signature[32:64], common.LeftPadBytes(tx.S.Bytes(), 32))
signature[64] = vb
pubk, err := crypto.RecoverPubkey(common.LeftPadBytes(crypto.SignedHash(tx, chainid), 32), signature)
if err != nil {
log.Info("recover failed for tx", "index", i, "err", err)
} else {
froms[i] = common.CopyBytes(crypto.Keccak256(pubk[1:])[12:])
log.Info("recover address is ", hex.EncodeToString(froms[i]))
}
//task := &XTaskSecp256k1RPubkey{
// Msg: tx.TxHash.Hash,
// Rsig: crypto.BytesCombine(common.LeftPadBytes(tx.R.Data, 32), common.LeftPadBytes(tx.S.Data, 32), []byte{vb}),
//}
//tasks[i] = task
}
response := new(metacrypter.BatchRecoverTxResponse)
response.RecoverdTx = req.RawTx
//resps, err := xecc.XeccInstance().BatchSecp256k1RecoverPubkey(tasks)
//if err != nil {
// return response, err
//}
for i := 0; i < len(response.RecoverdTx); i++ {
a := metatypes.BytesToAddress(froms[i])
response.RecoverdTx[i].From = &a
}
return response, nil
}
func RegisterCrypter(server *grpc.Server) {
metacrypter.RegisterCrypterServiceServer(server, &CrypterServer{})
}
package xecc
import (
. "github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/types"
)
func (x *Xecc) BatchSecp256k1RecoverPubkey(tasks []*XTaskSecp256k1RPubkey) ([]*XTaskSecp256k1RPubkey, error) {
var eng Engine
eng = x.cpue
var tall = make([]XTask, len(tasks))
for i := 0; i < len(tasks); i++ {
tall[i] = tasks[i]
}
res, e := eng.ProcessBatch(tall)
var xs = make([]*XTaskSecp256k1RPubkey, 0)
for _, t := range res {
xs = append(xs, t.(*XTaskSecp256k1RPubkey))
}
return xs, e
}
func (x *Xecc) BatchSecp256k1RecoverableSign(tasks []*XTaskSecp256k1RSign) ([]*XTaskSecp256k1RSign, error) {
var eng Engine
eng = x.cpue
var tall = make([]XTask, len(tasks))
for i := 0; i < len(tasks); i++ {
tall[i] = tasks[i]
}
res, e := eng.ProcessBatch(tall)
var xs = make([]*XTaskSecp256k1RSign, 0)
for _, t := range res {
xs = append(xs, t.(*XTaskSecp256k1RSign))
}
return xs, e
}
func (x *Xecc) BatchSecp256k1Sign(tasks []*XTaskSecp256k1Sign) ([]*XTaskSecp256k1Sign, error) {
var eng Engine
eng = x.cpue
var tall = make([]XTask, len(tasks))
for i := 0; i < len(tasks); i++ {
tall[i] = tasks[i]
}
res, e := eng.ProcessBatch(tall)
var xs = make([]*XTaskSecp256k1Sign, 0)
for _, t := range res {
xs = append(xs, t.(*XTaskSecp256k1Sign))
}
return xs, e
}
func (x *Xecc) BatchSecp256k1Verify(tasks []*XTaskSecp256k1Verify) ([]*XTaskSecp256k1Verify, error) {
var eng Engine
eng = x.cpue
var tall = make([]XTask, len(tasks))
for i := 0; i < len(tasks); i++ {
tall[i] = tasks[i]
}
res, e := eng.ProcessBatch(tall)
var xs = make([]*XTaskSecp256k1Verify, 0)
for _, t := range res {
xs = append(xs, t.(*XTaskSecp256k1Verify))
}
return xs, e
}
func (x *Xecc) BatchEcdsaSign(tasks []*XTaskEcdsa256Sign) ([]*XTaskEcdsa256Sign, error) {
var eng Engine
eng = x.cpue
var tall = make([]XTask, len(tasks))
for i := 0; i < len(tasks); i++ {
tall[i] = tasks[i]
}
res, e := eng.ProcessBatch(tall)
var xs = make([]*XTaskEcdsa256Sign, 0)
for _, t := range res {
xs = append(xs, t.(*XTaskEcdsa256Sign))
}
return xs, e
}
func (x *Xecc) BatchEcdsaVerify(tasks []*XTaskEcdsa256Verify) ([]*XTaskEcdsa256Verify, error) {
var eng Engine
eng = x.cpue
var tall = make([]XTask, len(tasks))
for i := 0; i < len(tasks); i++ {
tall[i] = tasks[i]
}
res, e := eng.ProcessBatch(tall)
var xs = make([]*XTaskEcdsa256Verify, 0)
for _, t := range res {
xs = append(xs, t.(*XTaskEcdsa256Verify))
}
return xs, e
}
func (x *Xecc) BatchSM2Sign(tasks []*XTaskSM2P256Sign) ([]*XTaskSM2P256Sign, error) {
var eng Engine
eng = x.cpue
var tall = make([]XTask, len(tasks))
for i := 0; i < len(tasks); i++ {
tall[i] = tasks[i]
}
res, e := eng.ProcessBatch(tall)
var xs = make([]*XTaskSM2P256Sign, 0)
for _, t := range res {
xs = append(xs, t.(*XTaskSM2P256Sign))
}
return xs, e
}
func (x *Xecc) BatchSM2Verify(tasks []*XTaskSM2P256Verify) ([]*XTaskSM2P256Verify, error) {
var eng Engine
eng = x.cpue
var tall = make([]XTask, len(tasks))
for i := 0; i < len(tasks); i++ {
tall[i] = tasks[i]
}
res, e := eng.ProcessBatch(tall)
var xs = make([]*XTaskSM2P256Verify, 0)
for _, t := range res {
xs = append(xs, t.(*XTaskSM2P256Verify))
}
return xs, e
}
package cpu
import (
"github.com/CaduceusMetaverseProtocol/MetaCryptor/crypto"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/engine"
. "github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/types"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/common/log"
"sync"
)
var (
cpuEngine = &CPUEngine{}
)
type CPUEngine struct {
softTask chan *TaskWithReport
closed chan struct{}
ready bool
mux sync.Mutex
initOnce sync.Once
}
func GetInstance() *CPUEngine {
cpuEngine.mux.Lock()
defer cpuEngine.mux.Unlock()
cpuEngine.initOnce.Do(func() {
cpuEngine.softTask = make(chan *TaskWithReport, 100000)
cpuEngine.closed = make(chan struct{})
cpuEngine.ready = true
go cpuEngine.softtask()
})
return cpuEngine
}
func (ce CPUEngine) Ready() bool {
return ce.ready
}
func (ce CPUEngine) Support(task XTask) bool {
return true
}
func (ce CPUEngine) Name() string {
return "cpu-engine"
}
func (ce CPUEngine) Process(task XTask) (XTask, error) {
if e := ce.doTask(task); e != nil {
return task, e
}
return task, nil
}
func (ce CPUEngine) ProcessA(twp *TaskWithReport) error {
if ce.Ready() {
return SafeWriteXTaskWithReport(ce.softTask, twp)
}
return engine.ErrNotReady
}
func (ce CPUEngine) ProcessBatch(tasks []XTask) ([]XTask, error) {
success := make([]XTask, 0, len(tasks))
failed := make([]XTask, 0, len(tasks))
sch := make(chan XTask)
fch := make(chan XTask)
for _, t := range tasks {
go func(task XTask) {
e := ce.doTask(task)
if e == nil {
SafeWriteXTask(sch, task)
} else {
SafeWriteXTask(fch, task)
}
}(t)
}
for {
select {
case n, ok := <-sch:
if !ok {
break
}
success = append(success, n)
case f, ok := <-fch:
if !ok {
break
}
failed = append(failed, f)
}
if (len(success) + len(failed)) == len(tasks) {
break
}
}
return success, nil
}
func (ce CPUEngine) doTask(task XTask) error {
var err error
switch t := task.(type) {
case *XTaskSecp256k1RPubkey:
log.Info("recover pubkey with v", t.Rsig[64])
t.Pubkey, err = crypto.RecoverPubkey(t.Msg, t.Rsig)
if err != nil {
log.Error("recover pubkey failed", "err=", err)
} else {
t.Address = crypto.Keccak256(t.Pubkey[1:])[12:]
}
case *XTaskSecp256k1RSign:
t.Rsig, err = crypto.RecoverableSign(t.Msg, t.Privk)
case *XTaskSecp256k1Sign:
t.Sig, err = crypto.Secp256k1Sign(t.Msg, t.Privk)
case *XTaskSecp256k1Verify:
t.Verify, err = crypto.Secp256k1Verify(t.Msg, t.Pubkey, t.Sig)
case *XTaskEcdsa256Sign:
t.Sig, err = crypto.EcdsaP256Sign(t.Msg, t.Privk)
case *XTaskEcdsa256Verify:
t.Verify, err = crypto.EcdsaP256Verify(t.Msg, t.Pubkey, t.Sig)
case *XTaskSM2P256Sign:
t.Sig, err = crypto.SM2Sign(t.Msg, t.Privk)
case *XTaskSM2P256Verify:
t.Verify, err = crypto.SM2Verify(t.Msg, t.Pubkey, t.Sig)
default:
err = engine.ErrUnsupport
}
return err
}
func (ce CPUEngine) softtask() {
for {
select {
case s, ok := <-ce.softTask:
if !ok {
return
}
t := s.XTask
if e := ce.doTask(t); e == nil {
s.Report()
}
case <-ce.closed:
return
}
}
}
package cpu
import (
"github.com/CaduceusMetaverseProtocol/MetaCryptor/crypto"
)
func (ce *CPUEngine) Secp256k1RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
return crypto.RecoverPubkey(msg, sig)
}
func (ce *CPUEngine) Secp256k1RecoverableSign(msg []byte, key []byte) ([]byte, error) {
return crypto.RecoverableSign(msg, key)
}
func (ce *CPUEngine) Secp256k1Sign(msg []byte, key []byte) ([]byte, error) {
return crypto.Secp256k1Sign(msg, key)
}
func (ce *CPUEngine) Secp256k1Verify(msg []byte, sign []byte, pubkey []byte) (bool, error) {
return crypto.Secp256k1Verify(msg, pubkey, sign)
}
func (ce *CPUEngine) EcdsaSign(msg []byte, key []byte) ([]byte, error) {
return crypto.EcdsaP256Sign(msg, key)
}
func (ce *CPUEngine) EcdsaVerify(msg []byte, sign []byte, pubkey []byte) (bool, error) {
return crypto.EcdsaP256Verify(msg, pubkey, sign)
}
func (ce *CPUEngine) SM2Sign(msg []byte, key []byte) ([]byte, error) {
return crypto.SM2Sign(msg, key)
}
func (ce *CPUEngine) SM2Verify(msg []byte, sign []byte, pubkey []byte) (bool, error) {
return crypto.SM2Verify(msg, pubkey, sign)
}
package engine
import (
"errors"
)
var (
ErrUnsupport = errors.New("unsupported function")
ErrNotReady = errors.New("engine is not ready")
)
// +build opencl
package opencl
/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L . -loclsp -lOpenCL
#include "oclsp.h"
#include <string.h>
*/
import "C"
import (
"errors"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/engine"
. "github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/types"
_ "github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/engine/opencl/statik"
"github.com/rakyll/statik/fs"
"io/ioutil"
"sync"
"time"
"unsafe"
)
const (
clfsname = "/k.cl"
verifyOk = 1
cl_success = 1
msgLength = 32
rsignLength = 65
signLength = 64
pubkeyLength = 65
openclCPU = 1
openclGPU = 0
)
type OclMsg [msgLength]byte
type OclRecoverableSignature [rsignLength]byte
type OclSignature [signLength]byte
type OclPubkey [pubkeyLength]byte
var (
ocle = &OclEngine{}
ErrNotAlready = errors.New("OpenCL not already")
ErrLengthNotMatch = errors.New("param length not matched")
ErrCallFunctionFailed = errors.New("call function failed")
)
type OclEngine struct {
init sync.Once
mux sync.Mutex
already bool
closed chan struct{}
verifytask *basetask
recovertask *basetask
}
func GetInstance() *OclEngine {
ocle.mux.Lock()
defer ocle.mux.Unlock()
ocle.init.Do(func() {
code, e := getCLSourcode()
if e == nil {
go func() {
var codelen C.int = C.int(len(code))
var c_code *C.uchar = (*C.uchar)(unsafe.Pointer(&code[0]))
ret := C.secp256_ocl_init(c_code, codelen, openclGPU)
if ret == 0 {
ocle.already = true
ocle.closed = make(chan struct{})
ocle.recovertask = newBaseTask()
ocle.verifytask = newBaseTask()
go ocle.routine()
}
}()
}
})
return ocle
}
func (ocl *OclEngine) Ready() bool {
return ocl.already
}
func (ocl *OclEngine) Support(xTask XTask) bool {
id := xTask.TaskId()
if id == FeatureSecp256k1RecoveryPubkey || id == FeatureSecp256k1Verify {
return true
}
return false
}
func (ocl *OclEngine) Name() string {
return "opencl-engine"
}
func (ocl *OclEngine) doTask(task XTask) (XTask, error) {
var e error
switch t := (task).(type) {
case *XTaskSecp256k1RPubkey:
t.Pubkey, e = ocl.OclSecp256RecoverPubkeyS(t.Msg, t.Rsig)
return t, nil
case *XTaskSecp256k1Verify:
t.Verify, e = ocl.OclSecp256VerifyS(t.Msg, t.Sig, t.Pubkey)
return t, nil
default:
e = engine.ErrUnsupport
}
return nil, e
}
func (ocl *OclEngine) doBatchTask(tasks []XTask) error {
var e error
var num = len(tasks)
switch tasks[0].(type) {
case *XTaskSecp256k1Verify:
var batch = make([]*XTaskSecp256k1Verify, len(tasks))
for i := 0; i < len(tasks); i++ {
batch[i] = tasks[i].(*XTaskSecp256k1Verify)
}
var (
batchMsg = make([]OclMsg, num)
batchSig = make([]OclSignature, num)
batchPub = make([]OclPubkey, num)
batchRet = make([]C.int, num)
)
for i := 0; i < num; i++ {
copy(batchMsg[i][:], batch[i].Msg)
copy(batchSig[i][:], batch[i].Sig)
copy(batchPub[i][:], batch[i].Pubkey)
}
e = ocl.batchOclSecp256Verify(batchMsg, batchSig, batchPub, batchRet)
if e != nil {
return e
}
for i := 0; i < num; i++ {
batch[i].Verify = (batchRet[i] == 1)
}
return nil
case *XTaskSecp256k1RPubkey:
var batch = make([]*XTaskSecp256k1RPubkey, len(tasks))
for i := 0; i < len(tasks); i++ {
batch[i] = tasks[i].(*XTaskSecp256k1RPubkey)
}
var (
batchMsg = make([]OclMsg, num)
batchRsig = make([]OclRecoverableSignature, num)
batchPub = make([]OclPubkey, num)
)
for i := 0; i < num; i++ {
copy(batchMsg[i][:], batch[i].Msg)
copy(batchRsig[i][:], batch[i].Rsig)
}
e = ocl.batchOclSecp256RecoverPubkey(batchMsg, batchRsig, batchPub)
if e != nil {
return e
}
for i := 0; i < num; i++ {
batch[i].Pubkey = make([]byte, pubkeyLength)
copy(batch[i].Pubkey, batchPub[i][:])
}
return nil
default:
e = engine.ErrUnsupport
}
return e
}
func (ocl *OclEngine) Process(task XTask) (XTask, error) {
if !ocl.Ready() {
return task, ErrNotAlready
} else {
t, e := ocl.doTask(task)
return t, e
}
}
func (ocl *OclEngine) ProcessA(twp *TaskWithReport) error {
if !ocl.Ready() {
return ErrNotAlready
}
ocl.mux.Lock()
defer ocl.mux.Unlock()
switch twp.XTask.(type) {
case *XTaskSecp256k1RPubkey:
ocl.recovertask.add(twp)
case *XTaskSecp256k1Verify:
ocl.verifytask.add(twp)
default:
return engine.ErrUnsupport
}
return nil
}
func (ocl *OclEngine) ProcessBatch(tasks []XTask) ([]XTask, error) {
if !ocl.Ready() {
return tasks, ErrNotAlready
} else {
e := ocl.doBatchTask(tasks)
return tasks, e
}
}
func getCLSourcode() ([]byte, error) {
statikFS, err := fs.New()
if err != nil {
return nil, err
}
// Access individual files by their paths.
r, err := statikFS.Open(clfsname)
if err != nil {
return nil, err
}
defer r.Close()
return ioutil.ReadAll(r)
}
func cArrayToGoArray(ca unsafe.Pointer, goArray []byte, size int) {
p := uintptr(ca)
for i := 0; i < size; i++ {
j := *(*byte)(unsafe.Pointer(p))
goArray[i] = j
p += unsafe.Sizeof(j)
}
}
func (ocl *OclEngine) batchOclSecp256RecoverPubkey(msg []OclMsg, sig []OclRecoverableSignature, recpub []OclPubkey) error {
msgcount := len(msg)
if msgcount != len(sig) || msgcount != len(recpub) {
return ErrLengthNotMatch
}
//fmt.Println("in oclEngine")
//for i := 0; i < msgcount; i++ {
// fmt.Printf("task ---> %d, msg = %s, rsig = %s\n", i, hex.EncodeToString(msg[i][:]),
// hex.EncodeToString(sig[i][:]))
//}
ocl.mux.Lock()
defer ocl.mux.Unlock()
var (
cmsg = (*C.ocl_msg)(unsafe.Pointer(&msg[0]))
csig = (*C.ocl_recoverable_signature)(unsafe.Pointer(&sig[0]))
cpub = (*C.ocl_pubkey)(unsafe.Pointer(&recpub[0]))
)
cret := C.secp256k1_ecdsa_recover_ocl(C.int(msgcount), csig, cmsg, cpub)
if cret != cl_success {
return ErrCallFunctionFailed
}
//fmt.Println("in oclEngine after recover ")
//for i := 0; i < msgcount; i++ {
// fmt.Printf("task ---> %d, rpub = %s\n", i, hex.EncodeToString(recpub[i][:]))
//}
return nil
}
func (ocl *OclEngine) batchOclSecp256Verify(msg []OclMsg, sig []OclSignature, pubkey []OclPubkey, verifyall []C.int) error {
msgcount := len(msg)
if msgcount != len(sig) || msgcount != len(pubkey) {
return ErrLengthNotMatch
}
ocl.mux.Lock()
defer ocl.mux.Unlock()
var (
cmsg = (*C.ocl_msg)(unsafe.Pointer(&msg[0]))
csig = (*C.ocl_signature)(unsafe.Pointer(&sig[0]))
cpub = (*C.ocl_pubkey)(unsafe.Pointer(&pubkey[0]))
cverify = (*C.int)(unsafe.Pointer(&verifyall[0]))
)
cret := C.secp256k1_ecdsa_verify_ocl(C.int(msgcount), csig, cmsg, cpub, cverify)
if cret != cl_success {
return ErrCallFunctionFailed
}
return nil
}
func (ocl *OclEngine) OclSecp256RecoverPubkeyS(msg []byte, sig []byte) ([]byte, error) {
if !ocl.already {
return nil, ErrNotAlready
}
var (
batchMsg = make([]OclMsg, 1)
batchRsig = make([]OclRecoverableSignature, 1)
batchPub = make([]OclPubkey, 1)
)
copy(batchMsg[0][:], msg)
copy(batchRsig[0][:], sig)
err := ocl.batchOclSecp256RecoverPubkey(batchMsg, batchRsig, batchPub)
if err != nil {
return nil, err
}
return batchPub[0][:], nil
}
func (ocl *OclEngine) OclSecp256VerifyS(msg []byte, sig []byte, pubkey []byte) (bool, error) {
if !ocl.already {
return false, ErrNotAlready
}
var (
batchMsg = make([]OclMsg, 1)
batchSig = make([]OclSignature, 1)
batchPub = make([]OclPubkey, 1)
batchRet = make([]C.int, 1)
)
copy(batchMsg[0][:], msg)
copy(batchSig[0][:], sig)
copy(batchPub[0][:], pubkey)
err := ocl.batchOclSecp256Verify(batchMsg, batchSig, batchPub, batchRet)
if err != nil {
return false, err
}
if batchRet[0] == verifyOk {
return true, nil
}
return false, nil
}
func (ocl *OclEngine) routine() {
for {
timer := time.NewTicker(time.Millisecond * 100)
select {
case <-timer.C:
if ocl.verifytask.ready() {
ocl.mux.Lock()
t := ocl.verifytask
ocl.verifytask = newBaseTask()
ocl.mux.Unlock()
{
var batch = make([]*XTaskSecp256k1Verify, len(t.tasks))
var num = len(t.tasks)
for i := 0; i < num; i++ {
batch[i] = t.tasks[i].XTask.(*XTaskSecp256k1Verify)
}
var (
batchMsg = make([]OclMsg, num)
batchSig = make([]OclSignature, num)
batchPub = make([]OclPubkey, num)
batchRet = make([]C.int, num)
)
for i := 0; i < num; i++ {
copy(batchMsg[i][:], batch[i].Msg)
copy(batchSig[i][:], batch[i].Sig)
copy(batchPub[i][:], batch[i].Pubkey)
}
e := ocl.batchOclSecp256Verify(batchMsg, batchSig, batchPub, batchRet)
if e != nil {
//Todo: deal with error.
}
for i := 0; i < num; i++ {
batch[i].Verify = (batchRet[i] == 1)
t.tasks[i].Report()
}
}
}
if ocl.recovertask.ready() {
ocl.mux.Lock()
t := ocl.recovertask
ocl.recovertask = newBaseTask()
ocl.mux.Unlock()
{
var num = len(t.tasks)
var batch = make([]*XTaskSecp256k1RPubkey, num)
for i := 0; i < num; i++ {
batch[i] = t.tasks[i].XTask.(*XTaskSecp256k1RPubkey)
}
var (
batchMsg = make([]OclMsg, num)
batchRsig = make([]OclRecoverableSignature, num)
batchPub = make([]OclPubkey, num)
)
for i := 0; i < num; i++ {
copy(batchMsg[i][:], batch[i].Msg)
copy(batchRsig[i][:], batch[i].Rsig)
}
e := ocl.batchOclSecp256RecoverPubkey(batchMsg, batchRsig, batchPub)
if e != nil {
//Todo: deal with error.
}
for i := 0; i < num; i++ {
batch[i].Pubkey = make([]byte, pubkeyLength)
copy(batch[i].Pubkey, batchPub[i][:])
t.tasks[i].Report()
}
}
}
case <-ocl.closed:
return
}
}
}
package opencl
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/types"
"io/ioutil"
"testing"
"time"
)
type recoverCase struct {
hash string
rsig string
pubk string
}
var recoverArray = []recoverCase{
{
hash: "31920d1ef030c8296c85c29e4658b1a29e2fea41af7ddad24dc6bc59c6e23c8d",
rsig: "ccc8e751834ddacc76773c9638f506e049840166eb025152ec5fb7d34b50feb06d95e1f220c8031ed73e8608f09f5de14cddb8122c3c0ec4ce26c42a2274e80b01",
pubk: "0481903830e01769fe48c372c1c02ce7fefbf042c3fde1f1cb74d3ada4465e26eeacb1f020b347614ab7e2dedb71e2efaa89e2a8661960839f72f6dde95d5eff3f",
},
{
hash: "e5312bc72030bb1c356e29f6047bd663e663d096ada0beb858081a4d3b55bf12",
rsig: "290a4d4e585f28db796dae3ced74130fabffead3b5c2923304e1761fb9ca936a09728351c56a4294df0c1fc387931d5cff7f59eadb1084bace16af61a341ef8601",
pubk: "0481903830e01769fe48c372c1c02ce7fefbf042c3fde1f1cb74d3ada4465e26eeacb1f020b347614ab7e2dedb71e2efaa89e2a8661960839f72f6dde95d5eff3f",
},
{
hash: "e04ab1e1892445ed18c7caa515e593e69eddea7250a9076bffbbc6aac87593ae",
rsig: "f8e53a45b4607cc4044439b4caac56179df941543f8bab6c6be6de681f7e1ee467591d058ab8660cf103b89ea749e75e2cd3c2b34fac4b3620b1b37b0542a72500",
pubk: "0481903830e01769fe48c372c1c02ce7fefbf042c3fde1f1cb74d3ada4465e26eeacb1f020b347614ab7e2dedb71e2efaa89e2a8661960839f72f6dde95d5eff3f",
},
{
hash: "72804c483b95fb866712ca175bd431214f46916fad5437b577772b0dd135e9f3",
rsig: "8fe82a947d922451f2fe2011bb63311248ff79fb9a88d2d28d3779ae80b7090664d9990c1f3077ca4f691af9594974f0be979a3801f65705757b86344fbe2b6601",
pubk: "0481903830e01769fe48c372c1c02ce7fefbf042c3fde1f1cb74d3ada4465e26eeacb1f020b347614ab7e2dedb71e2efaa89e2a8661960839f72f6dde95d5eff3f",
},
{
hash: "0824caafe5252483719d49ce28e0968d5f927d24ce96b31c5de48d0133ab3373",
rsig: "507f3caa9b0a3ccbf0e063fa21f0e765dab423a667268d9ce7101d2b8034e6fc44cb391b950fe8306e07b46e8df8bc9e10dd12c44100382861420d7f315db80f00",
pubk: "0481903830e01769fe48c372c1c02ce7fefbf042c3fde1f1cb74d3ada4465e26eeacb1f020b347614ab7e2dedb71e2efaa89e2a8661960839f72f6dde95d5eff3f",
},
}
func init() {
e := GetInstance()
for !e.Ready() {
fmt.Println("wait opencl init")
time.Sleep(time.Second)
}
}
func TestGetCLCode(t *testing.T) {
origin, err := ioutil.ReadFile("code/k.cl")
if err != nil {
t.Error("read origin data failed")
}
fsk, err := getCLSourcode()
if err != nil {
t.Error("get fsk data failed")
}
if bytes.Compare(origin, fsk) != 0 {
ioutil.WriteFile("fsk.cl", fsk, 0755)
t.Error("content compare failed")
}
}
func TestRecover(t *testing.T) {
ocl := GetInstance()
strhash := "e5312bc72030bb1c356e29f6047bd663e663d096ada0beb858081a4d3b55bf12"
strsig := "290a4d4e585f28db796dae3ced74130fabffead3b5c2923304e1761fb9ca936a09728351c56a4294df0c1fc387931d5cff7f59eadb1084bace16af61a341ef8601"
strpub := "0481903830e01769fe48c372c1c02ce7fefbf042c3fde1f1cb74d3ada4465e26eeacb1f020b347614ab7e2dedb71e2efaa89e2a8661960839f72f6dde95d5eff3f"
//error pub
//strpub := "0481903830e01769fe48c372c1c02ce7fefbf042c3fde1f1cb74d3ada4465e26eeacb1f020b347614ab7e2dedb71e2efaa89e2a8661960839f72f6dde95d5eff3s"
var msg, sig []byte
msg, _ = hex.DecodeString(strhash)
sig, _ = hex.DecodeString(strsig)
expectpub, _ := hex.DecodeString(strpub)
ts := time.Now().Nanosecond()
pub, err := ocl.OclSecp256RecoverPubkeyS(msg, sig)
if err != nil {
t.Error("Recover failed")
}
te := time.Now().Nanosecond()
if bytes.Compare(pub, expectpub) != 0 {
t.Error("compare failed")
t.Log("pub", hex.EncodeToString(pub))
}
fmt.Printf("recover cost %dus\n", (te-ts)/1000)
}
func TestVerify(t *testing.T) {
strhash := "02030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021"
strsig := "e8a97e31f8f5dde21b7394b190ed149ba0e28ddfdd44a170d21eb60f37bd132c04909be5273908befbe6166a9cb3f38fbb19c8cfff1d1561f4d61dfa0c499a81"
strpub := "041d17bd8d96b4bdf49dd1436e5af4f0bd3bff939df8cf8fdc1f621e3c89de2a47111eb88b4bb89f180702a8bc744d5a37615965713d1fdfff000c2a62b4aea409"
// error pub
//strpub := "041d17bd8d96b4bdf49dd1436e5af4f0bd3bff939df8cf8fdc1f621e3c89de2a47111eb88b4bb89f180702a8bc744d5a37615965713d1fdfff000c2a62b4aea404"
var msg, sig []byte
msg, _ = hex.DecodeString(strhash)
sig, _ = hex.DecodeString(strsig)
pub, _ := hex.DecodeString(strpub)
ts := time.Now().Nanosecond()
verify, err := GetInstance().OclSecp256VerifyS(msg, sig, pub)
if err != nil || !verify {
t.Error("Verify failed")
} else {
t.Log("Verify successful")
}
te := time.Now().Nanosecond()
fmt.Printf("verify cost %dus\n", (te-ts)/1000)
}
func TestProcess(t *testing.T) {
var tasks = make([]types.XTask, 0)
var okpubs = make([][]byte, 0)
for _, info := range recoverArray {
task := &types.XTaskSecp256k1RPubkey{}
task.Msg, _ = hex.DecodeString(info.hash)
task.Rsig, _ = hex.DecodeString(info.rsig)
pub, _ := hex.DecodeString(info.pubk)
tasks = append(tasks, task)
okpubs = append(okpubs, pub)
}
for i, tm := range tasks {
fmt.Println("test index ", i)
ts, e := GetInstance().Process(tm)
if e != nil {
t.Error("process failed", e)
}
if bytes.Compare(okpubs[i], tm.(*types.XTaskSecp256k1RPubkey).Pubkey) != 0 {
fmt.Println("compare pubkey failed", "got", hex.EncodeToString(tm.(*types.XTaskSecp256k1RPubkey).Pubkey), "expect ", hex.EncodeToString(okpubs[i]))
} else {
fmt.Println("tm got correct pubkey")
}
if bytes.Compare(okpubs[i], ts.(*types.XTaskSecp256k1RPubkey).Pubkey) != 0 {
fmt.Println("compare pubkey failed", "ret got", hex.EncodeToString(ts.(*types.XTaskSecp256k1RPubkey).Pubkey), "expect ", hex.EncodeToString(okpubs[i]))
} else {
fmt.Println("return value got correct pubkey")
}
}
}
func TestProcessBatch(t *testing.T) {
var tasks = make([]types.XTask, 0)
var okpubs = make([][]byte, 0)
for _, info := range recoverArray {
task := &types.XTaskSecp256k1RPubkey{}
task.Msg, _ = hex.DecodeString(info.hash)
task.Rsig, _ = hex.DecodeString(info.rsig)
pub, _ := hex.DecodeString(info.pubk)
tasks = append(tasks, task)
okpubs = append(okpubs, pub)
}
rets, e := GetInstance().ProcessBatch(tasks)
if e != nil {
t.Error("process failed", e)
}
for i, m := range rets {
if bytes.Compare(okpubs[i], m.(*types.XTaskSecp256k1RPubkey).Pubkey) != 0 {
t.Error("compare pubkey failed", "got", hex.EncodeToString(m.(*types.XTaskSecp256k1RPubkey).Pubkey), "expect ", hex.EncodeToString(okpubs[i]))
} else {
fmt.Println("return value ok, task", i)
}
}
for i, m := range tasks {
if bytes.Compare(okpubs[i], m.(*types.XTaskSecp256k1RPubkey).Pubkey) != 0 {
t.Error("compare pubkey failed", "got", hex.EncodeToString(m.(*types.XTaskSecp256k1RPubkey).Pubkey), "expect ", hex.EncodeToString(okpubs[i]))
} else {
fmt.Println("param value ok, task", i)
}
}
}
#ifndef OCLSP_H
#define OCLSP_H
typedef struct {
unsigned char data[65];
} ocl_recoverable_signature;
typedef struct {
unsigned char data[64];
} ocl_signature;
typedef struct {
unsigned char data[32];
} ocl_msg;
typedef struct {
unsigned char data[65];
} ocl_pubkey;
int secp256_ocl_init(unsigned char *code, int codelen, int mode);
int secp256_ocl_destory();
int secp256k1_ecdsa_recover_ocl(int count, ocl_recoverable_signature *rsigall,
ocl_msg *msgall, ocl_pubkey *pubkeyall);
int secp256k1_ecdsa_verify_ocl(int count, ocl_signature *sigall,
ocl_msg *msg32all, ocl_pubkey *pubkeyall, int *resall);
#endif /*OCLSP_H*/
This diff is collapsed.
// +build opencl
package opencl
/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L . -loclsp -lOpenCL
#include "oclsp.h"
*/
import "C"
import (
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/types"
"sync"
"time"
)
const (
defaultMaxBuff = 100000
defaultMaxIdle = time.Millisecond * 300
defaultMaxWait = time.Second * 2
)
type basetask struct {
rwmux sync.RWMutex
busy bool
lastm time.Time
firstm time.Time
tasks []*types.TaskWithReport
}
func (b basetask) add(task *types.TaskWithReport) {
b.rwmux.Lock()
defer b.rwmux.Unlock()
if len(b.tasks) == 0 {
b.firstm = time.Now()
}
b.tasks = append(b.tasks, task)
b.lastm = time.Now()
}
func (b basetask) len() int {
b.rwmux.RLock()
defer b.rwmux.RUnlock()
return len(b.tasks)
}
func (b basetask) ready() bool {
b.rwmux.RLock()
defer b.rwmux.RUnlock()
return len(b.tasks) >= defaultMaxBuff || // buffer is full
(len(b.tasks) > 0 && time.Now().After(b.firstm.Add(defaultMaxWait))) || // first item wait timeout
(len(b.tasks) > 0 && time.Now().After(b.lastm.Add(defaultMaxIdle))) // task idle timeout
}
func newBaseTask() *basetask {
return &basetask{
tasks: make([]*types.TaskWithReport, 0),
}
}
package xecc
import (
. "github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/types"
)
type Session struct {
xecc *Xecc
result chan XTask
closeCh chan struct{}
}
func (s *Session) AddTask(task XTask) error {
ts := MakeTaskWithReport(task, s.result)
return s.xecc.addTask(ts)
}
func (s *Session) GetResult() chan XTask {
return s.result
}
func (s *Session) closed() bool {
select {
case _, ok := <-s.closeCh:
if !ok {
return true
}
default:
return false
}
return false
}
// Close called by user.
func (s *Session) Close() {
if !s.closed() {
close(s.closeCh)
}
}
package types
func SafeWriteXTask(ch chan XTask, task XTask) error {
var err error
defer func() {
if r := recover(); r != nil {
// use closed channel
err = ErrChanClosed
}
}()
select {
case ch <- task:
err = nil
default:
err = ErrChanIsFull
}
return err
}
func SafeWriteXTaskWithReport(ch chan *TaskWithReport, task *TaskWithReport) error {
var err error
defer func() {
if r := recover(); r != nil {
// use closed channel
err = ErrChanClosed
}
}()
select {
case ch <- task:
err = nil
default:
err = ErrChanIsFull
}
return err
}
package types
import (
"errors"
)
var (
ErrChanIsFull = errors.New("channel is full")
ErrChanClosed = errors.New("channel is closed")
ErrRequestTimeout = errors.New("request timeout")
)
type FeatureId byte
const (
FeatureBase FeatureId = iota
FeatureSecp256k1RecoveryPubkey
FeatureSecp256k1RecoverableSign
FeatureSecp256k1Sign
FeatureSecp256k1Verify
FeatureEcdsaP256Sign
FeatureEcdsaP256Verify
FeatureSM2Sign
FeatureSM2Verify
)
type XTask interface {
TaskName() string
TaskId() FeatureId
}
type XTaskSecp256k1RPubkey struct {
Msg []byte
Rsig []byte
Pubkey []byte
Address []byte
}
func (x *XTaskSecp256k1RPubkey) TaskName() string {
return "Secp256K1-Recover-Pubkey"
}
func (x *XTaskSecp256k1RPubkey) TaskId() FeatureId {
return FeatureSecp256k1RecoveryPubkey
}
type XTaskSecp256k1RSign struct {
Msg []byte
Privk []byte
Rsig []byte
}
func (x *XTaskSecp256k1RSign) TaskName() string {
return "Secp256K1-Recoverable-Sign"
}
func (x *XTaskSecp256k1RSign) TaskId() FeatureId {
return FeatureSecp256k1RecoverableSign
}
type XTaskSecp256k1Sign struct {
Msg []byte
Privk []byte
Sig []byte
}
func (x *XTaskSecp256k1Sign) TaskName() string {
return "Secp256K1-Sign"
}
func (x *XTaskSecp256k1Sign) TaskId() FeatureId {
return FeatureSecp256k1Sign
}
type XTaskSecp256k1Verify struct {
Msg []byte
Sig []byte
Pubkey []byte
Verify bool
}
func (x *XTaskSecp256k1Verify) TaskName() string {
return "Secp256K1-Verify"
}
func (x *XTaskSecp256k1Verify) TaskId() FeatureId {
return FeatureSecp256k1Verify
}
type XTaskEcdsa256Sign struct {
Msg []byte
Privk []byte
Sig []byte
}
func (x *XTaskEcdsa256Sign) TaskName() string {
return "EcdsaP256-Sign"
}
func (x *XTaskEcdsa256Sign) TaskId() FeatureId {
return FeatureEcdsaP256Sign
}
type XTaskEcdsa256Verify struct {
Msg []byte
Sig []byte
Pubkey []byte
Verify bool
}
func (x *XTaskEcdsa256Verify) TaskName() string {
return "EcdsaP256-Verify"
}
func (x *XTaskEcdsa256Verify) TaskId() FeatureId {
return FeatureEcdsaP256Verify
}
type XTaskSM2P256Sign struct {
Msg []byte
Privk []byte
Sig []byte
}
func (x *XTaskSM2P256Sign) TaskName() string {
return "SM2P256-Sign"
}
func (x *XTaskSM2P256Sign) TaskId() FeatureId {
return FeatureSM2Sign
}
type XTaskSM2P256Verify struct {
Msg []byte
Sig []byte
Pubkey []byte
Verify bool
}
func (x *XTaskSM2P256Verify) TaskName() string {
return "SM2P256-Verify"
}
func (x *XTaskSM2P256Verify) TaskId() FeatureId {
return FeatureSM2Verify
}
type TaskWithReport struct {
XTask
ch chan XTask
}
func (t *TaskWithReport) Report() error {
return SafeWriteXTask(t.ch, t.XTask)
}
func MakeTaskWithReport(task XTask, report chan XTask) *TaskWithReport {
return &TaskWithReport{
task,
report,
}
}
type Engine interface {
Name() string
Ready() bool
Support(XTask) bool
Process(XTask) (XTask, error)
ProcessA(*TaskWithReport) error
ProcessBatch([]XTask) ([]XTask, error)
}
package xecc
import (
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/engine/cpu"
"github.com/CaduceusMetaverseProtocol/MetaCryptor/xecc/types"
"sync"
)
var (
xeccHandle = &Xecc{}
)
type Xecc struct {
cpue types.Engine
wg sync.WaitGroup
mux sync.Mutex
close chan struct{}
initOnce sync.Once
}
func XeccInstance() *Xecc {
xeccHandle.mux.Lock()
defer xeccHandle.mux.Unlock()
xeccHandle.initOnce.Do(func() {
xeccHandle.cpue = cpu.GetInstance()
xeccHandle.close = make(chan struct{})
})
return xeccHandle
}
func (x *Xecc) Secp256k1RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
return cpu.GetInstance().Secp256k1RecoverPubkey(msg, sig)
}
func (x *Xecc) Secp256k1RecoverableSign(msg []byte, key []byte) ([]byte, error) {
return cpu.GetInstance().Secp256k1RecoverableSign(msg, key)
}
func (x *Xecc) Secp256k1Sign(msg []byte, key []byte) ([]byte, error) {
return cpu.GetInstance().Secp256k1Sign(msg, key)
}
func (x *Xecc) Secp256k1Verify(msg []byte, sign []byte, pubkey []byte) (bool, error) {
return cpu.GetInstance().Secp256k1Verify(msg, sign, pubkey)
}
func (x *Xecc) EcdsaSign(msg []byte, key []byte) ([]byte, error) {
return cpu.GetInstance().EcdsaSign(msg, key)
}
func (x *Xecc) EcdsaVerify(msg []byte, sign []byte, pubkey []byte) (bool, error) {
return cpu.GetInstance().EcdsaVerify(msg, sign, pubkey)
}
func (x *Xecc) SM2Sign(msg []byte, key []byte) ([]byte, error) {
return cpu.GetInstance().SM2Sign(msg, key)
}
func (x *Xecc) SM2Verify(msg []byte, sign []byte, pubkey []byte) (bool, error) {
return cpu.GetInstance().SM2Verify(msg, sign, pubkey)
}
func (x *Xecc) Process(task types.XTask) (types.XTask, error) {
return x.cpue.Process(task)
}
func (x *Xecc) AsyncSession() *Session {
s := &Session{
xecc: x,
result: make(chan types.XTask, 100000),
closeCh: make(chan struct{}),
}
return s
}
func (x *Xecc) addTask(tws *types.TaskWithReport) error {
return x.cpue.ProcessA(tws)
}
.idea
.vscode
protocol
gen
MIT License
Copyright (c) 2022 CaduceusMetaverseProtocol
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Protobuf generated go files
PROTO_GO_FILES = $(shell find . -path -prune -o -type f -name '*.pb.go' -print | grep -v vendor)
#PROTO_GO_FILES = $(patsubst %.proto, %.pb.go, $(PROTO_FILES))
DEST=${PWD}
BIN=protocol
.PHONY: all build generate deps clean lint
all: build generate lint
build: $(PROTO_GO_FILES)
@buf build
lint: generate main.go
@go build -o $(BIN)
generate:
@buf generate
deps:
@go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
@go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
@go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
@go install github.com/bufbuild/buf/cmd/buf@v1.9.0
clean:
@rm -f $(PROTO_GO_FILES) $(BIN)
@rm -rf gen
This diff is collapsed.
# MetaProtocol
Define base protocol-buffer.
Please read [Guide](ProtobufStyle.md) first when you modify the *.proto* files.
# Add new module proto
1. install cloudstd
```go
go install github.com/slavovojacek/cloudstd@latest
```
2. add new module
```go
cloudstd proto --package "cmp.xxx.v1" --resource "shelf,shelves"
```
## Modules
/\
/ \
/ \
ring/gateway contract
/ \
/ \
/ \
<--------------
validator
#!/bin/bash
modulename=${1:-""}
cloudstd proto --package "meta.$modulename.v1" --resource "shelf,shelves"
// Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
package gogoproto;
import "google/protobuf/descriptor.proto";
option java_package = "com.google.protobuf";
option java_outer_classname = "GoGoProtos";
option go_package = "github.com/gogo/protobuf/gogoproto";
extend google.protobuf.EnumOptions {
optional bool goproto_enum_prefix = 62001;
optional bool goproto_enum_stringer = 62021;
optional bool enum_stringer = 62022;
optional string enum_customname = 62023;
optional bool enumdecl = 62024;
}
extend google.protobuf.EnumValueOptions {
optional string enumvalue_customname = 66001;
}
extend google.protobuf.FileOptions {
optional bool goproto_getters_all = 63001;
optional bool goproto_enum_prefix_all = 63002;
optional bool goproto_stringer_all = 63003;
optional bool verbose_equal_all = 63004;
optional bool face_all = 63005;
optional bool gostring_all = 63006;
optional bool populate_all = 63007;
optional bool stringer_all = 63008;
optional bool onlyone_all = 63009;
optional bool equal_all = 63013;
optional bool description_all = 63014;
optional bool testgen_all = 63015;
optional bool benchgen_all = 63016;
optional bool marshaler_all = 63017;
optional bool unmarshaler_all = 63018;
optional bool stable_marshaler_all = 63019;
optional bool sizer_all = 63020;
optional bool goproto_enum_stringer_all = 63021;
optional bool enum_stringer_all = 63022;
optional bool unsafe_marshaler_all = 63023;
optional bool unsafe_unmarshaler_all = 63024;
optional bool goproto_extensions_map_all = 63025;
optional bool goproto_unrecognized_all = 63026;
optional bool gogoproto_import = 63027;
optional bool protosizer_all = 63028;
optional bool compare_all = 63029;
optional bool typedecl_all = 63030;
optional bool enumdecl_all = 63031;
optional bool goproto_registration = 63032;
optional bool messagename_all = 63033;
optional bool goproto_sizecache_all = 63034;
optional bool goproto_unkeyed_all = 63035;
}
extend google.protobuf.MessageOptions {
optional bool goproto_getters = 64001;
optional bool goproto_stringer = 64003;
optional bool verbose_equal = 64004;
optional bool face = 64005;
optional bool gostring = 64006;
optional bool populate = 64007;
optional bool stringer = 67008;
optional bool onlyone = 64009;
optional bool equal = 64013;
optional bool description = 64014;
optional bool testgen = 64015;
optional bool benchgen = 64016;
optional bool marshaler = 64017;
optional bool unmarshaler = 64018;
optional bool stable_marshaler = 64019;
optional bool sizer = 64020;
optional bool unsafe_marshaler = 64023;
optional bool unsafe_unmarshaler = 64024;
optional bool goproto_extensions_map = 64025;
optional bool goproto_unrecognized = 64026;
optional bool protosizer = 64028;
optional bool compare = 64029;
optional bool typedecl = 64030;
optional bool messagename = 64033;
optional bool goproto_sizecache = 64034;
optional bool goproto_unkeyed = 64035;
}
extend google.protobuf.FieldOptions {
optional bool nullable = 65001;
optional bool embed = 65002;
optional string customtype = 65003;
optional string customname = 65004;
optional string jsontag = 65005;
optional string moretags = 65006;
optional string casttype = 65007;
optional string castkey = 65008;
optional string castvalue = 65009;
optional bool stdtime = 65010;
optional bool stdduration = 65011;
optional bool wktpointer = 65012;
}
syntax = "proto3";
package base.v1;
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
import "base/v1/resource.proto";
import "base/v1/meta.proto";
import "base/gogo.proto";
// BatchTx include one batchHash and all original tx contained in batch.
// it will broadcast to nebula over p2p module, and then save in p2p module.
// Amount metaprooftx make a batch tx, and generate a batch_hash,
message BatchTx {
Hash batch_hash = 1 [(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
repeated MetaProofTx txs = 2;
}
\ No newline at end of file
syntax = "proto3";
package base.v1;
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
import "base/v1/resource.proto";
import "base/v1/eth_tx.proto";
import "base/gogo.proto";
message EthBlockHeader {
Hash parent_hash = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Hash uncle_hash = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Hash block_hash = 3[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Address miner = 4[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
Hash state_root = 5[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Hash txs_root = 6[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Hash receipts_root = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
BigInt block_number = 8[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
Bloom block_bloom = 9;
BigInt difficulty = 10[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 gas_limit = 11;
uint64 gas_used = 12;
uint64 timestamp = 13;
bytes extra = 14;
Hash mix_hash = 15[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
BigInt block_nonce = 16[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt base_fee = 17[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
}
message EthBlockBody {
repeated EthTransaction txs = 1;
repeated EthBlockHeader uncles = 2;
}
message EthBlock {
EthBlockHeader header = 1;
repeated EthBlockHeader uncles = 2;
repeated EthTransaction txs = 3;
}
\ No newline at end of file
syntax = "proto3";
package base.v1;
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
import "base/v1/resource.proto";
import "base/gogo.proto";
option (gogoproto.messagename_all) = true;
message EthTxParam {
Address from = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
Address to = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
uint64 gas = 3;
BigInt gas_price = 4[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt max_fee_per_gas = 5[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt max_priority_fee_per_gas = 6[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt value = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 nonce = 8;
bytes input = 9;
AccessList accesslist = 10;
BigInt chain_id = 11[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
}
message EthLegacyTx {
uint64 nonce = 1;
BigInt gas_price = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 gas = 3;
Address to = 4[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
BigInt value = 5[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
bytes data = 6;
BigInt v = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt r = 8[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt s = 9[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
}
message EthAccessListTx {
BigInt chain_id = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 nonce = 2;
BigInt gas_price = 3[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 gas = 4;
Address to = 5[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
BigInt value = 6[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
bytes data = 7;
AccessList access_list = 8;
BigInt v = 9[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt r = 10[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt s = 11[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
}
message EthDynamicFeeTx {
BigInt chain_id = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 nonce = 2;
BigInt gas_tip_cap = 3[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt gas_fee_cap = 4[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 gas = 5;
Address to = 6[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
BigInt value = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
bytes data = 8;
AccessList access_list = 9;
BigInt v = 10[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt r = 11[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt s = 12[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
}
message EthTransaction {
google.protobuf.Any tx = 1; // one of EthLegacyTx, EthAccessListTx, EthDynamicFeeTx
}
// EthTxLog reference ethereum Log struct.
message EthTxLog {
Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
repeated Hash topics = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
bytes data = 3;
uint64 block_number = 4;
Hash tx_hash = 5[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
uint32 tx_index = 6;
Hash block_hash = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
uint32 log_index = 8;
bool removed = 9;
}
message EthReceipt {
uint32 type = 1;
bytes root = 2;
uint64 status = 3;
uint64 cumulative_gas_used = 4;
Bloom bloom = 5;
repeated EthTxLog logs = 6;
Hash tx_hash = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Address contract_address = 8[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
uint64 gas_used = 9;
Hash block_hash = 10[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
BigInt block_number = 11[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint32 tx_index = 12;
}
syntax = "proto3";
package base.v1;
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
import "base/v1/resource.proto";
import "base/gogo.proto";
option (gogoproto.messagename_all) = true;
message MetaProof{
bytes rset = 1;
bytes wset = 2;
bytes proof = 3;
int64 state_block_num = 4;
}
message MetaTxBase {
// tx_type used to type tx.
uint32 tx_type = 1;
BigInt chain_id = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 nonce = 3;
BigInt gas_price = 4[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint64 gas = 5;
Address to = 6[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
BigInt value = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
bytes data = 8;
AccessList access_list = 9;
BigInt v = 10[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt r = 11[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
BigInt s = 12[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
Address from = 13[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
//google.protobuf.Timestamp receive_time = 14; `protobuf:"bytes,1,opt,name=Name,proto3"`
// expire block used to ignore execute tx when it is packaged in expired_block.
BigInt expired_block = 15[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
Hash tx_hash = 16[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
}
message MetaProofTx {
MetaTxBase base = 1;
MetaProof proof = 2;
}
message MetaTransaction {
google.protobuf.Any tx = 1;
}
message MetaBlockHeader {
Hash parent_hash = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Hash block_hash = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Address miner = 3[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
Hash state_root = 4[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Hash txs_root = 5[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Hash receipts_root = 6[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
BigInt block_number = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
Bloom block_bloom = 8;
uint64 gas_limit = 9;
uint64 gas_used = 10;
uint64 timestamp = 11;
bytes extra = 12;
}
message MetaBlockBody {
repeated MetaTransaction txs = 1;
}
message MetaBlock {
MetaBlockHeader header = 1;
repeated MetaTransaction txs = 2;
}
message MetaTxLog {
Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
repeated Hash topics = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
bytes data = 3;
uint64 block_number = 4;
Hash tx_hash = 5[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
uint32 tx_index = 6;
Hash block_hash = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
uint32 log_index = 8;
bool removed = 9;
}
message MetaReceipt {
uint32 type = 1;
bytes root = 2;
uint64 status = 3;
uint64 cumulative_gas_used = 4;
Bloom bloom = 5;
repeated MetaTxLog logs = 6;
Hash tx_hash = 7[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
Address contract_address = 8[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
uint64 gas_used = 9;
Hash block_hash = 10[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
BigInt block_number = 11[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
uint32 tx_index = 12;
}
\ No newline at end of file
syntax = "proto3";
package base.v1;
import "google/protobuf/descriptor.proto";
extend google.protobuf.FieldOptions {
uint32 bytes_size = 50000; // define bytes data size.
}
\ No newline at end of file
syntax = "proto3";
package base.v1;
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
import "base/gogo.proto";
// import "google/protobuf/descriptor.proto";
// import "github.com/gogo/protobuf/gogoproto/gogo.proto";
// import "base/v1/options.proto";
message Bytes32 {
bytes data = 1;
}
message BigInt {
bytes data = 1;
// bytes data = 1 [(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaProtocol/custom/types.BigInt"][(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
}
message Hash {
bytes hash = 1;
}
message Address {
bytes address = 1;
}
message RLPData {
bytes data = 1;
}
message Account {
Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
uint64 nonce = 2;
BigInt balance = 3 [(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.BigInt"];
Hash state_root = 4[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
}
message Bloom {
bytes data = 1;
}
message AccessTuple {
Address address = 1[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Address"];
repeated Hash storage_keys = 2[(gogoproto.customtype) = "github.com/CaduceusMetaverseProtocol/MetaTypes/types.Hash"];
}
message AccessList {
repeated AccessTuple access_list = 1;
}
\ No newline at end of file
version: v1
deps:
- buf.build/gogo/protobuf
# - buf.build/googleapis/googleapis
# - buf.build/acme/paymentapis
breaking:
use:
- FILE
lint:
use:
- DEFAULT
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/ring/v1 (interfaces: GreeterClient)
// Package mock_v1 is a generated GoMock package.
package benchmark
import (
context "context"
reflect "reflect"
ringv1 "github.com/CaduceusMetaverseProtocol/MetaProtocol/gen/proto/go/ring/v1"
gomock "github.com/golang/mock/gomock"
grpc "google.golang.org/grpc"
)
// MockGreeterClient is a mock of GreeterClient interface.
type MockGreeterClient struct {
ctrl *gomock.Controller
recorder *MockGreeterClientMockRecorder
}
// MockGreeterClientMockRecorder is the mock recorder for MockGreeterClient.
type MockGreeterClientMockRecorder struct {
mock *MockGreeterClient
}
// NewMockGreeterClient creates a new mock instance.
func NewMockGreeterClient(ctrl *gomock.Controller) *MockGreeterClient {
mock := &MockGreeterClient{ctrl: ctrl}
mock.recorder = &MockGreeterClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockGreeterClient) EXPECT() *MockGreeterClientMockRecorder {
return m.recorder
}
// SayHello mocks base method.
func (m *MockGreeterClient) SayHello(arg0 context.Context, arg1 *ringv1.HelloRequest, arg2 ...grpc.CallOption) (*ringv1.HelloReply, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "SayHello", varargs...)
ret0, _ := ret[0].(*ringv1.HelloReply)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// SayHello indicates an expected call of SayHello.
func (mr *MockGreeterClientMockRecorder) SayHello(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SayHello", reflect.TypeOf((*MockGreeterClient)(nil).SayHello), varargs...)
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
version: v1
directories:
- baseapi
- crypterapi
- ethrpcapi
- nebulaapi
- p2papi
- ringapi
- sentryapi
#- txcheckerapi
\ No newline at end of file
# Generated by buf. DO NOT EDIT.
version: v1
version: v1
breaking:
use:
- FILE
lint:
use:
- DEFAULT
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
recover from is used in ring module, if recover failed, the from will return with 0x00...00
# Generated by buf. DO NOT EDIT.
version: v1
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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