Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Feature/chaincode #88

Merged
merged 2 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 127 additions & 25 deletions blockchain/service/http_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ func (h *HttpHandler) GetTokenBalance(ctx *gin.Context) {
h.Error(ctx, string(b), ctx.Request.RequestURI, fmt.Sprintf("blockchain:%v is not supported", blockChainCode))
return
}
res, err := h.blockChainClients[blockChainCode].TokenBalance(blockChainCode, codeHash, addr, abi)
res, err := h.blockChainClients[blockChainCode].TokenBalance(blockChainCode, addr, codeHash, abi)
if err != nil {
h.Error(ctx, r.String(), ctx.Request.RequestURI, err.Error())
return
Expand Down Expand Up @@ -449,6 +449,101 @@ func (h *HttpHandler) SendRawTx(ctx *gin.Context) {
h.Success(ctx, string(b), res, ctx.Request.RequestURI)
}

func (h *HttpHandler) SendRawTx1(ctx *gin.Context) {
b, err := io.ReadAll(ctx.Request.Body)
if err != nil {
h.Error(ctx, "", ctx.Request.RequestURI, err.Error())
return
}

backup := make(map[string]any, 5)
root := gjson.ParseBytes(b)
blockChainCode := root.Get("chain").Int()
backup["chainCode"] = blockChainCode
signedTx := root.Get("signed_tx").String()
backup["signed"] = signedTx
backup["id"] = time.Now().UnixMicro()
from := root.Get("from").String()
backup["from"] = from
to := root.Get("to").String()
backup["to"] = to
extra := root.Get("extra").String()
backup["extra"] = extra

if _, ok := h.blockChainClients[blockChainCode]; !ok {
h.Error(ctx, string(b), ctx.Request.RequestURI, fmt.Sprintf("blockchain:%v is not supported", blockChainCode))
return
}

defer func(backup map[string]any, chainCode int64) {
bs, _ := json.Marshal(backup)
msg := &kafka.Message{Topic: fmt.Sprintf("%v-%v", h.kafkaCfg.Topic, chainCode), Partition: h.kafkaCfg.Partition, Key: []byte(fmt.Sprintf("%v", time.Now().UnixNano())), Value: bs}
h.sendCh <- []*kafka.Message{msg}
}(backup, blockChainCode)

res, err := h.blockChainClients[blockChainCode].SendRawTransaction(blockChainCode, signedTx)
if err != nil {
h.Error(ctx, string(b), ctx.Request.RequestURI, err.Error())
backup["status"] = 0
return
}
backup["status"] = 1
backup["response"] = res

m := make(map[string]any)
//{
// "id": 1,
// "jsonrpc": "2.0",
// "result": "0x2a7e11bcb80ea248e09975c48da02b7d0c29d42521d6e9e65e112358132134"
//}
if chain.GetChainCode(blockChainCode, "ETH", nil) || chain.GetChainCode(blockChainCode, "BSC", nil) || chain.GetChainCode(blockChainCode, "POLYGON", nil) {
hash := gjson.Parse(res).Get("result").String()
m["hash"] = hash
} else if chain.GetChainCode(blockChainCode, "TRON", nil) {
//{
// "result": {
// "code": "SUCCESS",
// "message": "SUCCESS",
// "transaction": {
// "txID": "a6a4c7d5b7f2c3871f4a8271f8b690c324f8c350d0e4b9abaddfe7c2294a1737",
// "raw_data": {
// // 其他原始数据
// },
// "signature": [
// // 签名信息
// ],
// // 其他交易信息
// }
// }
//}

//{"code":"SIGERROR","txid":"77ddfa7093cc5f745c0d3a54abb89ef070f983343c05e0f89e5a52f3e5401299","message":"56616c6964617465207369676e6174757265206572726f723a206d69737320736967206f7220636f6e7472616374"}

root := gjson.Parse(res)
if root.Get("result.code").Exists() {
status := root.Get("result.code").String()
if status == "SUCCESS" {
m["status"] = status
id := root.Get("result.transaction.txID").String()
m["hash"] = id
} else {
h.Error(ctx, string(b), ctx.Request.RequestURI, res)
return
}

} else {
h.Error(ctx, string(b), ctx.Request.RequestURI, res)
return
}

} else {
h.Error(ctx, string(b), ctx.Request.RequestURI, fmt.Sprintf("blockchain:%v is not supported", blockChainCode))
return
}

h.Success(ctx, string(b), m, ctx.Request.RequestURI)
}

// HandlerReq 有用户自定义请求内容,然后直接发送到节点 ,和eth_call 函数无关
func (h *HttpHandler) HandlerReq(ctx *gin.Context) {
b, err := io.ReadAll(ctx.Request.Body)
Expand Down Expand Up @@ -653,28 +748,30 @@ func (h *HttpHandler) GetBalance1(ctx *gin.Context) {
}

r := make(map[string]any)
r["utxo"] = ""
r["address"] = addr
var nonce string
//{"jsonrpc":"2.0","id":1,"result":"0x20ef7755b4d96faf5"}
if chain.GetChainCode(blockChainCode, "ETH", nil) {
if chain.GetChainCode(blockChainCode, "ETH", nil) || chain.GetChainCode(blockChainCode, "BSC", nil) || chain.GetChainCode(blockChainCode, "POLYGON", nil) {
balance := gjson.Parse(res).Get("result").String()
balance, _ = util.HexToInt(balance)
r["balance"] = balance
resNonce, err := h.blockChainClients[blockChainCode].Nonce(blockChainCode, addr, tag)
if err == nil && len(resNonce) > 1 {
nonce = gjson.Parse(resNonce).Get("result").String()
nonce, _ = util.HexToInt(nonce)
}
} else if chain.GetChainCode(blockChainCode, "TRON", nil) {
// {"balance":309739}
balance := gjson.Parse(res).Get("balance").String()
r["balance"] = balance

} else if chain.GetChainCode(blockChainCode, "BSC", nil) {
balance := gjson.Parse(res).Get("result").String()
balance, _ = util.HexToInt(balance)
r["balance"] = balance
} else if chain.GetChainCode(blockChainCode, "POLYGON", nil) {
balance := gjson.Parse(res).Get("result").String()
balance, _ = util.HexToInt(balance)
r["balance"] = balance
nonce = "0"
} else {
h.Error(ctx, string(b), ctx.Request.RequestURI, fmt.Sprintf("blockchain:%v is not supported", blockChainCode))
return
}
//r["totalAmount"] = r["balance"]
r["nonce"] = nonce

h.Success(ctx, string(b), r, ctx.Request.RequestURI)
}
Expand All @@ -696,37 +793,40 @@ func (h *HttpHandler) GetTokenBalance1(ctx *gin.Context) {
h.Error(ctx, string(b), ctx.Request.RequestURI, fmt.Sprintf("blockchain:%v is not supported", blockChainCode))
return
}
res, err := h.blockChainClients[blockChainCode].TokenBalance(blockChainCode, codeHash, addr, abi)
res, err := h.blockChainClients[blockChainCode].TokenBalance(blockChainCode, addr, codeHash, abi)
if err != nil {
h.Error(ctx, r.String(), ctx.Request.RequestURI, err.Error())
return
}

m := make(map[string]any)
m["utxo"] = ""
m["address"] = addr
var nonce string

// {"balance":"1233764293093","decimals":6,"name":"Tether USD","symbol":"USDT"}
if chain.GetChainCode(blockChainCode, "ETH", nil) {
balance := gjson.Parse(res).Get("balance").String()
if chain.GetChainCode(blockChainCode, "ETH", nil) || chain.GetChainCode(blockChainCode, "BSC", nil) || chain.GetChainCode(blockChainCode, "POLYGON", nil) {
balance := gjson.Parse(res).Get("result").String()
balance, _ = util.HexToInt(balance)
m["balance"] = balance

resNonce, err := h.blockChainClients[blockChainCode].Nonce(blockChainCode, addr, "latest")
if err == nil && len(resNonce) > 1 {
nonce = gjson.Parse(resNonce).Get("result").String()
nonce, _ = util.HexToInt(nonce)
}
} else if chain.GetChainCode(blockChainCode, "TRON", nil) {
//{"balance":"74305000412789","decimals":"6"}
balance := gjson.Parse(res).Get("balance").String()
m["balance"] = balance

} else if chain.GetChainCode(blockChainCode, "BSC", nil) {
balance := gjson.Parse(res).Get("balance").String()
m["balance"] = balance

} else if chain.GetChainCode(blockChainCode, "POLYGON", nil) {
balance := gjson.Parse(res).Get("balance").String()
m["balance"] = balance

nonce = "0"
} else {
h.Error(ctx, string(b), ctx.Request.RequestURI, fmt.Sprintf("blockchain:%v is not supported", blockChainCode))
return
}

//m["totalAmount"] = m["balance"]
m["nonce"] = nonce

h.Success(ctx, r.String(), m, ctx.Request.RequestURI)
}

Expand Down Expand Up @@ -933,6 +1033,7 @@ func (h *HttpHandler) Success(c *gin.Context, req string, resp interface{}, path
h.log.Printf("path=%v,req=%v,resp=%v\n", path, req, resp)
mp := make(map[string]interface{})
mp["code"] = SUCCESS
mp["message"] = "ok"
mp["data"] = resp
c.JSON(200, mp)
}
Expand All @@ -943,6 +1044,7 @@ func (h *HttpHandler) Error(c *gin.Context, req string, path string, err string)
h.log.Errorf("path=%v,req=%v,err=%v\n", path, req, err)
mp := make(map[string]interface{})
mp["code"] = FAIL
mp["data"] = err
mp["message"] = err
mp["data"] = ""
c.JSON(200, mp)
}
39 changes: 37 additions & 2 deletions blockchain/service/tron/tron_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (

func Init() blockchain.API {
cfg := config.LoadConfig("./../../../cmd/blockchain/config_tron.json")
return NewTron(cfg.Cluster[205], 205, xlog.NewXLogger())
return NewTron(cfg.Cluster[198], 198, xlog.NewXLogger())
}

func TestTron_Balance(t *testing.T) {
Expand All @@ -26,7 +26,7 @@ func TestTron_Balance(t *testing.T) {

func TestTron_TokenBalance(t *testing.T) {
s := Init()
resp, err := s.TokenBalance(205, "TWGZbjofbTLY3UCjCV4yiLkRg89zLqwRgi", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "")
resp, err := s.TokenBalance(198, "TDGLAKnr2SeYJHht6YxrtZqfRrVR9RFdwV", "TBo8ZFTG13PZZTgSVbuTVBi5FrCZjDedFU", "")

if err != nil {
t.Error(err)
Expand Down Expand Up @@ -89,3 +89,38 @@ func TestTron_GetBlockReceiptByBlockNumber(t *testing.T) {
c := Init()
log.Println(c.GetBlockReceiptByBlockNumber(205, "45611899"))
}

func TestTron_SendRawTransaction(t *testing.T) {
c := Init()
tx := `
{
"raw_data": {
"contract": [
{
"parameter": {
"value": {
"amount": 1000,
"owner_address": "41608f8da72479edc7dd921e4c30bb7e7cddbe722e",
"to_address": "41e9d79cc47518930bc322d9bf7cddd260a0260a8d"
},
"type_url": "type.googleapis.com/protocol.TransferContract"
},
"type": "TransferContract"
}
],
"ref_block_bytes": "5e4b",
"ref_block_hash": "47c9dc89341b300d",
"expiration": 1591089627000,
"timestamp": 1591089567635
},
"raw_data_hex": "0a025e4b220847c9dc89341b300d40f8fed3a2a72e5a66080112620a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412310a1541608f8da72479edc7dd921e4c30bb7e7cddbe722e121541e9d79cc47518930bc322d9bf7cddd260a0260a8d18e8077093afd0a2a72e"
}
`

resp, err := c.SendRawTransaction(198, tx)
if err != nil {
t.Error(err)
} else {
t.Log(resp)
}
}
3 changes: 2 additions & 1 deletion cmd/blockchain/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (

func main() {
var configPath string
flag.StringVar(&configPath, "blockchain", "./cmd/blockchain/config.json", "The system file of config")
flag.StringVar(&configPath, "blockchain", "./cmd/blockchain/blockchain_config.json", "The system file of config")
flag.Parse()
if len(configPath) < 1 {
panic("can not find config file")
Expand Down Expand Up @@ -73,6 +73,7 @@ func main() {
myRoot.POST("/block/latest", srv.GetLatestBlock1)
myRoot.POST("/gas/price", srv.GasPrice1)
myRoot.POST("/gas/estimateGas", srv.EstimateGas1)
myRoot.POST("/tx/sendRawTransaction", srv.SendRawTx1)

err := e.Run(fmt.Sprintf(":%v", cfg.Port))
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions cmd/easynode/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ func startBlockchain(configPath string, ctx context.Context) {
myRoot.POST("/block/latest", srv.GetLatestBlock1)
myRoot.POST("/gas/price", srv.GasPrice1)
myRoot.POST("/gas/estimateGas", srv.EstimateGas1)
myRoot.POST("/tx/sendRawTransaction", srv.SendRawTx1)

err := e.Run(fmt.Sprintf(":%v", cfg.Port))
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions store/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const (
TronTopic = "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
EthTopic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
EthTransferSingleTopic = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62"
EthTransferBatchTopic = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb"
PolygonTopic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
)

Expand Down
Loading