first commit
This commit is contained in:
75
internal/blockchain/blockchain.go
Normal file
75
internal/blockchain/blockchain.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package blockchain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type IChainServer interface {
|
||||
AddAddress(address string, msg any)
|
||||
RemoveAddress(address string)
|
||||
Listen(symbol string, ch chan any)
|
||||
Transfer(symbol string, msg any) error
|
||||
Stop()
|
||||
}
|
||||
|
||||
type BlockChainServer struct {
|
||||
mu sync.Mutex
|
||||
chains map[string]IChainServer // "ETH", "TRON", "BTC"
|
||||
}
|
||||
|
||||
func NewBlockChainServer() *BlockChainServer {
|
||||
return &BlockChainServer{
|
||||
chains: make(map[string]IChainServer),
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BlockChainServer) RegisterChain(name string, chain IChainServer) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.chains[name] = chain
|
||||
}
|
||||
|
||||
func (b *BlockChainServer) AddAddress(chain, address string, msg any) {
|
||||
if srv, ok := b.chains[chain]; ok {
|
||||
srv.AddAddress(address, msg)
|
||||
fmt.Printf("✅ 添加监听地址: chain=%s, address=%s\n", chain, address)
|
||||
} else {
|
||||
fmt.Printf("⚠️ 链未注册: %s\n", chain)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BlockChainServer) RemoveAddress(chain, address string) {
|
||||
if srv, ok := b.chains[chain]; ok {
|
||||
srv.RemoveAddress(address)
|
||||
fmt.Printf("🗑️ 移除监听地址: chain=%s, address=%s\n", chain, address)
|
||||
} else {
|
||||
fmt.Printf("⚠️ 链未注册: %s\n", chain)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BlockChainServer) Listen(chain, symbol string, ch chan any) error {
|
||||
if srv, ok := b.chains[chain]; ok {
|
||||
go func() {
|
||||
srv.Listen(symbol, ch)
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("链未注册: %s", chain)
|
||||
}
|
||||
|
||||
func (b *BlockChainServer) Transfer(chain, symbol string, msg any) error {
|
||||
if srv, ok := b.chains[chain]; ok {
|
||||
fmt.Printf("💸 %s-%s发起转账: %+v\n", chain, symbol, msg)
|
||||
return srv.Transfer(symbol, msg)
|
||||
}
|
||||
return fmt.Errorf("链未注册: %s", chain)
|
||||
}
|
||||
|
||||
func (b *BlockChainServer) Stop(chain string) {
|
||||
if srv, ok := b.chains[chain]; ok {
|
||||
fmt.Printf("💸 关闭服务: %+v\n", chain)
|
||||
srv.Stop()
|
||||
}
|
||||
fmt.Printf("链未注册: %s", chain)
|
||||
}
|
||||
Reference in New Issue
Block a user