Browse Source

dcrwallet

476052856 6 years ago
parent
commit
1b8b3d1b62

+ 1 - 1
coinproxy.toml

@@ -14,6 +14,6 @@ HttpBindAddr =":15741"
 dbpath="/var/"
 
 [cointype]
-type=["BCC"]
+type=["DCR"]
 sigkey="coinsapi^&#@(*33"
 

BIN
coinsapi


+ 1 - 2
config.go

@@ -41,11 +41,10 @@ type databaseinfo struct {
 }
 
 type cointype struct {
-	Type []string
+	Type   []string
 	Sigkey string
 }
 
-
 func coinInit() {
 	runtime.GOMAXPROCS(CPUNUM)
 	flag.PrintDefaults()

+ 4 - 4
src/bucash/bucash.go

@@ -371,12 +371,13 @@ func (m BuCashApi) WalletInfo() ([]byte, error) {
 	err = errors.New(walletinfoResult.Error.Message)
 	return nil, err
 }
+
 //list unspent transaction outputs
 func (m BuCashApi) Listunspent(address []string) ([]map[string]interface{}, error) {
 
 	var unspentResult RpcUnspentResult
 
-	result, err := bucashRpc.RunCall("listunspent",1, 9999999, address)
+	result, err := bucashRpc.RunCall("listunspent", 1, 9999999, address)
 
 	if err != nil {
 		fmt.Println("Call listunspent fail:", err.Error())
@@ -397,7 +398,7 @@ func (m BuCashApi) Listunspent(address []string) ([]map[string]interface{}, erro
 	var unspentValue map[string]float64
 	unspentValue = make(map[string]float64)
 	for _, unspentInfo := range unspentResult.Result {
-		 addr := unspentInfo.Address
+		addr := unspentInfo.Address
 		if unspentValue[addr] == 0 {
 			unspentValue[addr] = unspentInfo.Amount
 		} else {
@@ -414,7 +415,7 @@ func (m BuCashApi) Listunspent(address []string) ([]map[string]interface{}, erro
 		requestData["Amount"] = value
 		outputsArr = append(outputsArr, requestData)
 	}
-	return outputsArr,nil
+	return outputsArr, nil
 
 }
 
@@ -448,7 +449,6 @@ func (m BuCashApi) SendRawTransaction(hexstring string) (string, error) {
 	return "", err
 }
 
-
 func (m BuCashApi) InitRpcConf(rpcuser string, rpcpassword string, rpchost string, rpcport int) bool {
 
 	bucashRpc.InitRpcConfig(rpcuser, rpcpassword, rpchost, rpcport)

+ 3 - 4
src/bucash/bucashcoins.go

@@ -307,10 +307,10 @@ func (m Bucash) ChainHeight(parm interface{}) ([]byte, error) {
 
 func (m Bucash) ListUnspent(parm interface{}) ([]byte, error) {
 	pjs := parm.(*simplejson.Json)
-	address,err := pjs.Get("address").StringArray()
-	if err != nil{
+	address, err := pjs.Get("address").StringArray()
+	if err != nil {
 		LOG("ERROR", "  input parm error:%v", err.Error())
-                return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, LISTUNSPENT_ERR, getErrMsg(LISTUNSPENT_ERR, nil))
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, LISTUNSPENT_ERR, getErrMsg(LISTUNSPENT_ERR, nil))
 	}
 	unspent, err := CoinApi.Listunspent(address)
 	if err != nil {
@@ -360,7 +360,6 @@ func (m Bucash) SendRawTransaction(parm interface{}) ([]byte, error) {
 	return jbuf, nil
 }
 
-
 func init() {
 	Register(NameCoin, &Bucash{})
 }

+ 418 - 0
src/dcrcash/dcrcash.go

@@ -0,0 +1,418 @@
+package dcrcash
+
+import (
+	"dcrcash/dcrcashRpc"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"math/rand"
+	"strconv"
+	"time"
+)
+
+type DcrCashApi struct {
+}
+
+func (m *DcrCashApi) InitRpcConf(rpcuser string, rpcpassword string, rpchost string, rpcport int) bool {
+	dcrcashRpc.InitRpcConf(rpcuser, rpcpassword, rpchost, rpcport)
+	return true
+}
+
+//get a new taddr
+func (m *DcrCashApi) WalletNewAddr() (string, error) {
+	var newaddr RpcResult
+	r := rand.NewSource(time.Now().UnixNano())
+	label := strconv.FormatInt(r.Int63(), 10)
+	fmt.Println(label)
+	dcrcashRpc.RunCall("walletpassphrase", Config.Walletpass.Passphrase, 3)
+	dcrcashRpc.RunCall("createnewaccount", label)
+	//time.Sleep(time.Second * 1)
+	result, err := dcrcashRpc.RunCall("getnewaddress", label)
+	if err != nil {
+		fmt.Println("Call getnewaddress fail:", err.Error())
+		return "", err
+	}
+
+	if err := json.Unmarshal([]byte(result), &newaddr); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return "", err
+	}
+
+	// success
+	if len(newaddr.Error.Message) == 0 {
+		return newaddr.Result, nil
+	}
+
+	err = errors.New(newaddr.Error.Message)
+	return "", err
+}
+
+//get PrivKey by taddr
+func (m *DcrCashApi) WalletDumpPrivKey(address string) (string, error) {
+
+	var key RpcResult
+
+	if len(address) == 0 {
+		fmt.Println("input address err:")
+		err := errors.New("input address error:")
+
+		return "", err
+	}
+
+	//
+	result, err := dcrcashRpc.RunCall("dumpprivkey", address)
+	fmt.Println("WalletDumpPrivKey>>>>>>>:", string(result))
+	if err != nil {
+		fmt.Println("Call dumpprivkey fail:", err.Error())
+		return "", err
+	}
+
+	if err := json.Unmarshal([]byte(result), &key); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return "", err
+	}
+
+	// success
+	if len(key.Error.Message) == 0 {
+		return key.Result, nil
+	}
+	err = errors.New(key.Error.Message)
+	return "", err
+}
+
+func (m *DcrCashApi) WalletInfo() ([]byte, error) {
+	var walletinfoResult WalletinfoResult
+	result, err := dcrcashRpc.RunCall("walletinfo")
+
+	fmt.Println(string(result))
+	if err != nil {
+		fmt.Println("Call walletinfo fail:", err.Error())
+		return nil, err
+	}
+	fmt.Println("WalletInfo->Unmarshal")
+	if err := json.Unmarshal([]byte(result), &walletinfoResult); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return nil, err
+	}
+
+	if len(walletinfoResult.Error.Message) == 0 {
+		var jbuf []byte
+		if jbuf, err = json.Marshal(walletinfoResult.Result); err != nil {
+			return nil, err
+		}
+		return jbuf, nil
+	}
+	err = errors.New(walletinfoResult.Error.Message)
+	return nil, err
+}
+
+func (m *DcrCashApi) WalletSetTxFee(amount float64) (bool, error) {
+	var settxfee Setfeeresult
+
+	result, err := dcrcashRpc.RunCall("settxfee", amount)
+	if err != nil {
+		fmt.Println("Call settxfee fail:", err.Error())
+		return false, err
+	}
+
+	if err := json.Unmarshal([]byte(result), &settxfee); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return false, err
+	}
+
+	if len(settxfee.Error.Message) == 0 {
+		return settxfee.Result, nil
+	}
+
+	err = errors.New(settxfee.Error.Message)
+	return false, err
+}
+
+func (m DcrCashApi) WalleGetBlockCount() (uint64, error) {
+
+	var blockcount Blockcountresult
+
+	//
+	result, err := dcrcashRpc.RunCall("getblockcount")
+
+	if err != nil {
+		fmt.Println("Call getblockcount fail:", err.Error())
+		return 0, err
+	}
+
+	if err := json.Unmarshal([]byte(result), &blockcount); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return 0, err
+	}
+
+	// success
+	if len(blockcount.Error.Message) == 0 {
+		return uint64(blockcount.Result), nil
+	}
+	err = errors.New(blockcount.Error.Message)
+	return 0, err
+}
+
+//get the server's total available balance
+func (m DcrCashApi) WalleGetBalance(account string) ([]byte, error) {
+
+	var liteBalance BalanceResult
+
+	// getbalance all
+	result, err := dcrcashRpc.RunCall("getbalance", account)
+	if err != nil {
+		fmt.Println("Call getbalance fail:", err.Error())
+		return nil, err
+	}
+
+	if err := json.Unmarshal([]byte(result), &liteBalance); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return nil, err
+	}
+	fmt.Println("WalleGetBalance:", len(liteBalance.Result.Balances))
+	// success
+	if len(liteBalance.Error.Message) == 0 {
+		var jbuf []byte
+		if jbuf, err = json.Marshal(liteBalance.Result.Balances); err != nil {
+			return nil, err
+		}
+		return jbuf, nil
+	}
+	err = errors.New(liteBalance.Error.Message)
+	return nil, err
+}
+
+//get block hash by index
+func (m DcrCashApi) WalletGetBlockHash(index uint64) (string, error) {
+
+	var Blockhash RpcResult
+
+	//get block hash by index
+	result, err := dcrcashRpc.RunCall("getblockhash", index)
+	if err != nil {
+		fmt.Println("Call getblockhash fail:", err.Error())
+		return "", err
+	}
+
+	if err := json.Unmarshal([]byte(result), &Blockhash); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return "", err
+	}
+
+	// success
+	if len(Blockhash.Error.Message) == 0 {
+		return Blockhash.Result, nil
+	}
+	err = errors.New(Blockhash.Error.Message)
+	return "", err
+}
+
+//get block time by hash;return:blocktime
+func (m DcrCashApi) WalletGetBlockTime(blockhash string) (uint64, error) {
+
+	var blockresult BlockResult
+
+	if len(blockhash) == 0 {
+		fmt.Println("input para err:")
+		err := errors.New("input para err")
+		return 0, err
+	}
+	//get block info by blockhash
+	result, err := dcrcashRpc.RunCall("getblock", blockhash)
+	if err != nil {
+		fmt.Println("Call getblock fail:", err.Error())
+		return 0, err
+	}
+
+	if err := json.Unmarshal([]byte(result), &blockresult); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return 0, err
+	}
+
+	// success
+	if len(blockresult.Error.Message) == 0 {
+
+		return uint64(blockresult.Result.Time), nil
+	}
+	err = errors.New(blockresult.Error.Message)
+	return 0, err
+}
+
+func (m *DcrCashApi) WalleListSinceBlock(blockhash string) ([]byte, error) {
+
+	var listtransactionsresult Listtransactionsresult
+
+	if len(blockhash) == 0 {
+		fmt.Println("input blockhash err:")
+		err := errors.New("input blockhash err")
+		return nil, err
+	}
+
+	//
+	result, err := dcrcashRpc.RunCall("listsinceblock", blockhash)
+	fmt.Println("WalleListSinceBlock Result:", string(result))
+	if err != nil {
+		fmt.Println("Call listsinceblock fail:", err.Error())
+		return nil, err
+	}
+
+	if err := json.Unmarshal([]byte(result), &listtransactionsresult); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return nil, err
+	}
+
+	// success
+	if len(listtransactionsresult.Error.Message) == 0 {
+
+		var jbuf []byte
+		if jbuf, err = json.Marshal(listtransactionsresult.Result.Transactions); err != nil {
+			return nil, err
+		}
+		return jbuf, nil
+	}
+	err = errors.New(listtransactionsresult.Error.Message)
+	return nil, err
+}
+
+//get block Height by hash;return:blocktime
+func (m DcrCashApi) WalletGetBlockHeight(blockhash string) (uint64, error) {
+
+	var blockresult BlockResult
+
+	if len(blockhash) == 0 {
+		fmt.Println("input para err:")
+		err := errors.New("input para err")
+		return 0, err
+	}
+	//get block info by blockhash
+	result, err := dcrcashRpc.RunCall("getblock", blockhash)
+	if err != nil {
+		fmt.Println("Call getblock fail:", err.Error())
+		return 0, err
+	}
+
+	if err := json.Unmarshal([]byte(result), &blockresult); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return 0, err
+	}
+
+	// success
+	if len(blockresult.Error.Message) == 0 {
+
+		return uint64(blockresult.Result.Height), nil
+	}
+	err = errors.New(blockresult.Error.Message)
+	return 0, err
+}
+
+//Sent an amount from an account to a zcash address.
+//The amount is a real and is rounded to the nearest 0.00000001.
+//Result:"transactionid" (string) The transaction id.
+func (m *DcrCashApi) WalleSendTo(toaddress string, amount float64, comment, commentto string) (string, error) {
+
+	var SendResult RpcResult
+
+	if len(toaddress) == 0 {
+		fmt.Println("input toaddress err:")
+		err := errors.New("input toaddress err")
+		return "", err
+	}
+	//fmt.Println("config.WalletInfo.Pripassphrase:", Config.Walletpass.Passphrase)
+	dcrcashRpc.RunCall("walletpassphrase", Config.Walletpass.Passphrase, 3)
+	result, err := dcrcashRpc.RunCall("sendtoaddress", toaddress, amount, "", "")
+	fmt.Println("WalleSendTo>>>>>>>>", string(result))
+	if err != nil {
+		fmt.Println("Call sendfrom fail:", err.Error())
+		return "", err
+	}
+
+	if err := json.Unmarshal([]byte(result), &SendResult); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return "", err
+	}
+
+	// success
+	if len(SendResult.Error.Message) == 0 {
+		return SendResult.Result, nil
+	}
+	err = errors.New(SendResult.Error.Message)
+	fmt.Println("WalleSendTo>>>>>>>>End....")
+	return strconv.Itoa(SendResult.Error.Code), err
+}
+
+//list unspent transaction outputs
+func (m DcrCashApi) Listunspent(address []string) ([]map[string]interface{}, error) {
+
+	var unspentResult RpcUnspentResult
+
+	result, err := dcrcashRpc.RunCall("listunspent", 1, 9999999, address)
+	fmt.Println("Listunspent Result:", string(result))
+	if err != nil {
+		fmt.Println("Call listunspent fail:", err.Error())
+		return nil, err
+	}
+
+	if err := json.Unmarshal([]byte(result), &unspentResult); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return nil, err
+	}
+
+	// success
+	if len(unspentResult.Error.Message) != 0 {
+		err = errors.New(unspentResult.Error.Message)
+		return nil, err
+	}
+
+	var unspentValue map[string]float64
+	unspentValue = make(map[string]float64)
+	for _, unspentInfo := range unspentResult.Result {
+		addr := unspentInfo.Address
+		if unspentValue[addr] == 0 {
+			unspentValue[addr] = unspentInfo.Amount
+		} else {
+			unspentValue[addr] += unspentInfo.Amount
+		}
+	}
+
+	outputsArr := make([]map[string]interface{}, 0)
+	for k, v := range unspentValue {
+		requestData := make(map[string]interface{})
+		requestData["address"] = k
+		valuestr := fmt.Sprintf("%.8f", v)
+		value, _ := strconv.ParseFloat(valuestr, 64)
+		requestData["Amount"] = value
+		outputsArr = append(outputsArr, requestData)
+	}
+	return outputsArr, nil
+
+}
+
+//Send Raw Transaction
+func (m DcrCashApi) SendRawTransaction(hexstring string) (string, error) {
+
+	var rawtransactioninfo RpcResult
+
+	if len(hexstring) == 0 {
+		fmt.Println("input para err:")
+		err := errors.New("input para err")
+		return "", err
+	}
+
+	result, err := dcrcashRpc.RunCall("sendrawtransaction", hexstring)
+	if err != nil {
+		fmt.Println("Call sendrawtransaction fail:", err.Error())
+		return "", err
+	}
+
+	if err := json.Unmarshal([]byte(result), &rawtransactioninfo); err != nil {
+		fmt.Println("Unmarshal err :", err.Error())
+		return "", err
+	}
+
+	if len(rawtransactioninfo.Error.Message) == 0 {
+
+		return rawtransactioninfo.Result, nil
+	}
+	err = errors.New(rawtransactioninfo.Error.Message)
+	return "", err
+}

+ 16 - 0
src/dcrcash/dcrcash.toml

@@ -0,0 +1,16 @@
+Title = "coinproxy"
+
+[walletinfo]
+WalletKey="scrub usual alchemy moon height eskimos palace deity boss runway present dawn examine torch mice owed physics perfect soya pixels woven logic items sequence aggravate textbook nobody envy adjust"
+
+[walletpass]
+passphrase="fuzamei888"
+
+[limit]
+fee="0.00000000"
+
+[rpc]
+rpcuser="rpcuser"
+rpcpassword="rpcpass"
+rpcHost="127.0.0.1"
+rpcPort=9110

+ 273 - 0
src/dcrcash/dcrcashRpc/dcrcashRpc.go

@@ -0,0 +1,273 @@
+package dcrcashRpc
+
+import (
+	"bytes"
+	"crypto/tls"
+	"crypto/x509"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io/ioutil"
+	"net"
+	"net/http"
+	"os"
+	"strconv"
+)
+
+//CoinDefaultProto  default coin protp
+const CoinDefaultProto string = "http"
+
+//CoinDefaultProto  default coin protp
+const CoinDefaultjsonrpc string = "1.0"
+
+//CoinDefaultid  default coin id
+const CoinDefaultid string = "curltest"
+
+// litecoin Host address
+var Host string = "localhost"
+
+//litecoin  port
+var Port int = 9110
+
+// litecoin address
+var User string = "rpcuser"
+
+//litecoin  Password
+var Password string = "rpcpass"
+
+type Request struct {
+	Jsonrpc string            `json:"jsonrpc"`
+	Method  string            `json:"method"`
+	Params  []json.RawMessage `json:"params"`
+	ID      interface{}       `json:"id"`
+}
+
+type Coin struct {
+	// Configuration options
+	username string
+	password string
+	proto    string
+	host     string
+	port     int
+	url      string
+	jsonrpc  string
+	// rawResponse string
+	responseData []byte
+	id           string
+	client       *http.Client
+}
+
+func NewCoin(coinUser, coinPasswd, coinHost, coinURL string, coinPort int) (cn *Coin, err error) {
+	cn = &Coin{
+		username: coinUser,
+		password: coinPasswd,
+		host:     coinHost,
+		port:     coinPort,
+		url:      coinURL,
+		proto:    CoinDefaultProto,
+		jsonrpc:  CoinDefaultjsonrpc,
+		id:       CoinDefaultid,
+	}
+	if len(coinHost) == 0 {
+		cn.host = "localhost"
+	}
+	if coinPort < 0 || coinPort > 65535 {
+		cn.port = 9110
+	}
+	cn.client = &http.Client{}
+	cn.client.Transport = &http.Transport{}
+	//cn.client, err = newHTTPCliet()
+
+	return cn, nil
+}
+
+func newHTTPCliet() (*http.Client, error) {
+	var dial func(network, addr string) (net.Conn, error)
+
+	var tlsConfig *tls.Config
+
+	pem, err := ioutil.ReadFile("/home/hdb/.dcrwallet/rpc.cert")
+	if err != nil {
+		return nil, err
+	}
+
+	pool := x509.NewCertPool()
+	if ok := pool.AppendCertsFromPEM(pem); !ok {
+		return nil, fmt.Errorf("invalid certificate file!!")
+	}
+	tlsConfig = &tls.Config{
+		RootCAs:            pool,
+		InsecureSkipVerify: false,
+	}
+	//fmt.Println(string(pem), tlsConfig.InsecureSkipVerify)
+	fmt.Fprintf(os.Stderr, "%s\n", string(pem), tlsConfig.InsecureSkipVerify)
+	client := http.Client{
+		Transport: &http.Transport{
+			Dial:            dial,
+			TLSClientConfig: tlsConfig,
+		},
+	}
+	return &client, nil
+}
+
+func (cn *Coin) access(jbuf []byte) (err error) {
+	if cn.client == nil {
+		err = errors.New("http client error")
+		return
+	}
+
+	cn.responseData = nil
+
+	var (
+		httpRequest *http.Request
+		resp        *http.Response
+	)
+	fmt.Println(string(jbuf))
+	addr := cn.proto + "://" + cn.host + ":" + strconv.Itoa(cn.port) + "/" + cn.url
+
+	httpRequest, err = http.NewRequest("POST", addr, bytes.NewReader(jbuf))
+	if err != nil {
+		fmt.Println(" http.NewRequest:", err.Error())
+		return
+	}
+	httpRequest.Close = true
+	httpRequest.Header.Set("Content-Type", "application/json")
+
+	httpRequest.SetBasicAuth(cn.username, cn.password)
+
+	if resp, err = cn.client.Do(httpRequest); err != nil {
+		fmt.Println(" cn.client.Do fail:", err.Error())
+		return
+	}
+
+	if resp.StatusCode != http.StatusOK {
+		err = errors.New(resp.Status)
+		fmt.Println(" resp.StatusCode:", err.Error())
+		//return
+	}
+
+	defer resp.Body.Close()
+	if cn.responseData, err = ioutil.ReadAll(resp.Body); err != nil {
+		fmt.Println("ioutil.ReadAll(resp.Body):", err.Error())
+		return
+	}
+	if len(cn.responseData) == 0 {
+		err = errors.New("response data is empty")
+		return
+	}
+	//fmt.Println("cn.responseData:", string(cn.responseData))
+	return
+}
+
+//Call run RPC command
+func RunCall(method string, args ...interface{}) (data []byte, err error) {
+	if method == "" {
+		err = errors.New("method is not set")
+		return
+	}
+
+	//
+	dcrCoin, err := NewCoin(User, Password, Host, "", Port)
+	if err != nil {
+		fmt.Println("dcrCoin.NewCoin fail", err.Error())
+		return nil, err
+	}
+	marsh1cmd, err := Marsha1cmd(method, args...)
+	if err != nil {
+		fmt.Println("dcrcashRpc RunCall Marsh1cmd fail", err.Error())
+		return nil, err
+	}
+	if err = dcrCoin.access(marsh1cmd); err == nil {
+		data = dcrCoin.responseData
+	}
+	return
+}
+
+func InitRpcConf(rpcuser string, rpcpassword string, rpchost string, rpcport int) bool {
+	fmt.Println("default rpc config:", rpcuser, rpcpassword, Host, Port)
+	if len(rpcuser) != 0 {
+		User = rpcuser
+	}
+
+	if len(rpcpassword) != 0 {
+		Password = rpcpassword
+	}
+	if len(rpchost) != 0 {
+		Host = rpchost
+	}
+	if rpcport != 0 {
+		Port = rpcport
+	}
+
+	fmt.Println("current rpc config:", User, Password, Host, Port)
+	return true
+}
+
+func Marsha1cmd(method string, args ...interface{}) ([]byte, error) {
+	/*rt := reflect.TypeOf(cmd)
+	method, ok := concreateTypeToMethod[rt]
+	if !ok {
+		str := fmt.Sprintf("%q is not registered", method)
+		return nil, error.Error(str)
+	}
+
+	rv := reflect.ValueOf(cmd)
+	if rv.IsNil() {
+		str := "the specified command is nil"
+		return nil, error.Error(str)
+	}
+
+	params := makeParams(rt.Elem(), rv.Elem())*/
+	if method == "" {
+		str := fmt.Sprintf("%q is not method", method)
+		return nil, errors.New(str)
+	}
+	params := make([]interface{}, 0, len(args))
+	for _, v := range args {
+		params = append(params, v)
+	}
+
+	//params := cmd["params"]
+	//params = []interface{}(Params)
+	rawCmd, err := NewRequest(1, method, params)
+	if err != nil {
+		return nil, err
+	}
+	return json.Marshal(rawCmd)
+}
+
+func NewRequest(id interface{}, method string, params []interface{}) (*Request, error) {
+	rawParams := make([]json.RawMessage, 0, len(params))
+	for _, param := range params {
+		marshalledparam, err := json.Marshal(param)
+		if err != nil {
+			return nil, err
+		}
+		rawMessage := json.RawMessage(marshalledparam)
+		rawParams = append(rawParams, rawMessage)
+	}
+
+	return &Request{
+		Jsonrpc: CoinDefaultjsonrpc,
+		ID:      id,
+		Method:  method,
+		Params:  rawParams,
+	}, nil
+}
+
+/*func makeParams(rt reflect.Type, rv reflect.Value) []interface{} {
+	numFields := rt.NumField()
+	params := make([]interface{}, 0, numFields)
+	for i := 0; i < numFields; i++ {
+		rtf := rt.Field(i)
+		rvf := rv.Field(i)
+		if rtf.Type.Kind() == reflect.Ptr {
+			if rvf.IsNil() {
+				break
+			}
+			rvf.Elem()
+		}
+		params = append(params, rvf.Interface())
+	}
+	return params
+}*/

+ 238 - 0
src/dcrcash/dcrcash_test.go

@@ -0,0 +1,238 @@
+package dcrcash
+
+import (
+	"crypto/sha1"
+	"encoding/hex"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"strings"
+	"testing"
+	"time"
+)
+
+func Test_newaddr(t *testing.T) {
+	client := http.DefaultClient
+	geturl := fmt.Sprintf(`http://localhost:15741/coinproxy/createaddr`)
+	//timestamp := fmt.Sprintf("%v", time.Now().Unix())
+
+	fmt.Printf("post url:%v", geturl)
+
+	//var b []byte
+	//postdata := fmt.Sprintf(`{"cointype":"BCC","timestamp":"%v"}`, timestamp)
+	postdata := fmt.Sprintf(`{"cointype":"DCR"}`)
+	request, err := http.NewRequest("POST", geturl, strings.NewReader(postdata))
+	if err != nil {
+		fmt.Printf("err:%s", err.Error())
+		return
+	}
+	resp, err := client.Do(request)
+	if err != nil {
+		fmt.Printf("err:%s", err.Error())
+		return
+	}
+
+	defer resp.Body.Close()
+	rbs, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		fmt.Printf("err:%s", err.Error())
+		return
+	}
+
+	fmt.Printf("read bytes:%v", string(rbs))
+
+	return
+}
+
+func Test_Balance(t *testing.T) {
+	client := http.DefaultClient
+	geturl := fmt.Sprintf(`http://localhost:15741/coinproxy/coinbalance`)
+	timestamp := fmt.Sprintf("%v", time.Now().Unix())
+	t.Logf("post url:%v", geturl)
+
+	//var b []byte
+	postdata := fmt.Sprintf(`{"cointype":"DCR","timestamp":"%v"}`, timestamp)
+	request, err := http.NewRequest("POST", geturl, strings.NewReader(postdata))
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+	resp, err := client.Do(request)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	defer resp.Body.Close()
+	rbs, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	t.Logf("read bytes:%v", string(rbs))
+	return
+}
+
+func Test_TransInfo(t *testing.T) {
+
+	//first get block height then test transinfo
+
+	client := http.DefaultClient
+	geturl := fmt.Sprintf(`http://localhost:15741/coinproxy/query/transinfo`)
+	timestamp := fmt.Sprintf("%v", time.Now().Unix())
+	t.Logf("post url:%v", geturl)
+
+	//var b []byte
+	postdata := fmt.Sprintf(`{"cointype":"DCR","starth":1,"endh":1243398,"timestamp":"%v"}`, timestamp)
+	request, err := http.NewRequest("POST", geturl, strings.NewReader(postdata))
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+	resp, err := client.Do(request)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	defer resp.Body.Close()
+	rbs, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	t.Logf("read bytes:%v", string(rbs))
+	return
+}
+
+func Test_ChainHeight(t *testing.T) {
+	client := http.DefaultClient
+	geturl := fmt.Sprintf(`http://localhost:15741/coinproxy/blockchain/height`)
+	timestamp := fmt.Sprintf("%v", time.Now().Unix())
+	t.Logf("post url:%v", geturl)
+
+	//var b []byte
+	postdata := fmt.Sprintf(`{"cointype":"DCR","timestamp":"%v"}`, timestamp)
+	request, err := http.NewRequest("POST", geturl, strings.NewReader(postdata))
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+	resp, err := client.Do(request)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	defer resp.Body.Close()
+	rbs, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	t.Logf("read bytes:%v", string(rbs))
+
+	return
+}
+
+func Test_ListUnspent(t *testing.T) {
+	client := http.DefaultClient
+	geturl := fmt.Sprintf(`http://localhost:15741/coinproxy/listunspent`)
+	timestamp := fmt.Sprintf("%v", time.Now().Unix())
+	t.Logf("post url:%v", geturl)
+
+	postdata := fmt.Sprintf(`{"cointype":"DCR","address":[2],"timestamp":"%v"}`, timestamp)
+	request, err := http.NewRequest("POST", geturl, strings.NewReader(postdata))
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+	resp, err := client.Do(request)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	defer resp.Body.Close()
+	rbs, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	t.Logf("read bytes:%v", string(rbs))
+
+	return
+}
+
+func Test_SendRawTransaction(t *testing.T) {
+	client := http.DefaultClient
+	geturl := fmt.Sprintf(`http://localhost:15741/coinproxy/sendrawtransaction`)
+	t.Logf("post url:%v", geturl)
+
+	//var b []byte
+	postdata := fmt.Sprintf(`{"cointype":"DCR","data":"a4db9908e6d01a347d2fe5040592851b0497da93fc5889e737daf5225f1d66c8","address":""}`)
+	request, err := http.NewRequest("POST", geturl, strings.NewReader(postdata))
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+	resp, err := client.Do(request)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	defer resp.Body.Close()
+	rbs, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	t.Logf("read bytes:%v", string(rbs))
+
+	return
+}
+
+func Test_TransferAccounts(t *testing.T) {
+	client := http.DefaultClient
+	geturl := fmt.Sprintf(`http://localhost:15741/coinproxy/sendcoins`)
+	timestamp := fmt.Sprintf("%v", time.Now().Unix())
+	t.Logf("post url:%v", geturl)
+
+	//var b []byte
+	postdata := fmt.Sprintf(`{"cointype":"DCR","amount":"0.5","address":"Dsk52C4m56pmAnNAhejXypVGBDTi5GDrHpb","timestamp":"%v","signature":"%v"}`, timestamp, Signature([]byte("/coinproxy/sendcoins"), timestamp))
+	request, err := http.NewRequest("POST", geturl, strings.NewReader(postdata))
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+	resp, err := client.Do(request)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	defer resp.Body.Close()
+	rbs, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		t.Errorf("err:%s", err.Error())
+		return
+	}
+
+	t.Logf("read bytes:%v", string(rbs))
+	return
+}
+
+func Signature(body []byte, timestamp string) string {
+
+	sha1Contain := sha1.New()
+	byteSha1 := append(body, append([]byte(timestamp), []byte("2017coins%^&#@(*33")...)...)
+	sha1Contain.Write(byteSha1)
+	localSig := hex.EncodeToString(sha1Contain.Sum(nil))
+	return localSig
+}

+ 368 - 0
src/dcrcash/dcrcashcoin.go

@@ -0,0 +1,368 @@
+package dcrcash
+
+import (
+	"encoding/json"
+	"fmt"
+	"strconv"
+	. "template"
+	"time"
+
+	simplejson "github.com/go-simplejson"
+	tml "github.com/toml-master"
+)
+
+var (
+	Config  config
+	CoinApi DcrCashApi
+	//Walletpass string
+)
+
+type DcrCash struct {
+	walletstatus bool
+}
+
+const (
+	NameCoin    = "DCR"
+	SendToError = "-32603"
+)
+
+func (m DcrCash) InitDriver(param interface{}) bool {
+	if m.initconfig() == false {
+		return false
+	}
+	go m.getwalletinfo()
+	return true
+}
+
+func (m DcrCash) initconfig() bool {
+	if _, err := tml.DecodeFile("./src/dcrcash/dcrcash.toml", &Config); err != nil {
+		fmt.Println(err)
+		return false
+	}
+
+	fmt.Printf("%+v\n", Config)
+	User := Config.Rpc.Rpcuser
+	Password := Config.Rpc.Rpcpassword
+	Host := Config.Rpc.Rpchost
+	Port := Config.Rpc.Rpcport
+	//Walletpass = Config.WalletInfo.Pripassphrase
+
+	CoinApi.InitRpcConf(User, Password, Host, Port)
+
+	initDcrError()
+
+	f, err := strconv.ParseFloat(Config.Limit.Fee, 64)
+	if err != nil {
+		LOG("ERROR", "init json error:%v", err.Error())
+		return false
+	}
+
+	fee := float64(f)
+	CoinApi.WalletSetTxFee(fee) //
+	return true
+}
+
+func (m DcrCash) getwalletinfo() bool {
+	fmt.Println("Walletinfo:")
+	m.walletstatus = false
+
+	for {
+		if m.walletstatus == false {
+			resp, err := CoinApi.WalletInfo()
+			if err != nil {
+				LOG("ERROR", "WalletInfo error:%v", err.Error())
+				time.Sleep(time.Second * 1)
+				continue
+			}
+
+			LOG("DEBUG", "walletInfo resp:%v", string(resp))
+			m.walletstatus = true
+		}
+
+		time.Sleep(time.Second)
+	}
+}
+
+func (m DcrCash) CoinBalance(parm interface{}) ([]byte, error) {
+	confirmedBalance, err := CoinApi.WalleGetBalance("*")
+	if err != nil {
+		LOG("ERROR", " GetBalance err:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETBALANCE_ERR, getErrMsg(GETBALANCE_ERR, nil))
+	}
+	var balance []account
+	if err = json.Unmarshal(confirmedBalance, &balance); err != nil {
+		LOG("ERROR", " inner json error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+	}
+	var totalConfirbalance float64
+	var totalUnconfirbalance float64
+	for _, vbalance := range balance {
+		if vbalance.Spendable != 0 {
+			totalConfirbalance += vbalance.Spendable
+		}
+		if vbalance.Unconfirmed != 0 {
+			totalUnconfirbalance += vbalance.Unconfirmed
+		}
+
+	}
+	var jbuf []byte
+	resp := make(map[string]interface{})
+	resp["confirmedbalance"] = totalConfirbalance
+	resp["unconfirmed"] = totalUnconfirbalance
+	resp["errcode"] = 0
+	resp["exact"] = 0
+	if jbuf, err = json.Marshal(resp); err != nil {
+		LOG("ERROR", "lite inner json error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+	}
+
+	return jbuf, nil
+}
+
+func (m DcrCash) CreateAddress(parm interface{}) ([]byte, error) {
+	addr, err := CoinApi.WalletNewAddr()
+	if err != nil {
+		LOG("ERROR", "  get new address error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETNEWADDRESS_ERR, getErrMsg(GETNEWADDRESS_ERR, nil))
+	}
+	if len(addr) != 0 {
+		//get key by the address
+		key, err := CoinApi.WalletDumpPrivKey(addr)
+
+		if err != nil {
+			LOG("ERROR", " dump private key error:%v", err.Error())
+			return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, DUMPPRIVKEY_ERR, getErrMsg(DUMPPRIVKEY_ERR, nil))
+		}
+		if len(key) != 0 {
+
+			var jbuf []byte
+			resp := make(map[string]interface{})
+			resp["address"] = addr
+			resp["privkey"] = key
+			resp["errcode"] = 0
+
+			if jbuf, err = json.Marshal(resp); err != nil {
+				LOG("ERROR", " inner json error:%v", err.Error())
+				return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+			}
+			return jbuf, nil
+		}
+		LOG("ERROR", " privkey is null error:%v")
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+	}
+	LOG("ERROR", " address is null error:%v")
+	return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+}
+
+func (m DcrCash) TransferAccounts(parm interface{}) ([]byte, error) {
+	pjs := parm.(*simplejson.Json)
+	amountTmp := pjs.Get("amount").MustString()
+	destination := pjs.Get("address").MustString()
+
+	if len(amountTmp) == 0 {
+		LOG("ERROR", " amount illeagal")
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, AMOUNT_ERR, getErrMsg(AMOUNT_ERR, nil))
+	}
+	f, err := strconv.ParseFloat(amountTmp, 64)
+	if err != nil {
+		LOG("ERROR", " inner json error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+	}
+
+	amount := float64(f)
+
+	transactionid, err := CoinApi.WalleSendTo(destination, amount, "", "")
+	if err != nil {
+		LOG("ERROR", " Send coin error:%v", err.Error())
+		fmt.Println(transactionid)
+		if transactionid == SendToError {
+			return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INSUFFICIENT_FUNDS_TRANSACTION_ERR, getErrMsg(INSUFFICIENT_FUNDS_TRANSACTION_ERR, nil))
+		}
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, SENDCOINS_ERR, getErrMsg(SENDCOINS_ERR, nil))
+	}
+
+	if len(transactionid) != 0 {
+		var jbuf []byte
+		resp := make(map[string]interface{})
+		resp["transcationids"] = []string{transactionid}
+		resp["errcode"] = 0
+		resp["msg"] = "ok"
+
+		if jbuf, err = json.Marshal(resp); err != nil {
+			LOG("ERROR", " inner json error:%v", err.Error())
+			return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+		}
+		return jbuf, nil
+	}
+	LOG("ERROR", " transactionid is null error:%v", err.Error())
+	return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+}
+
+func (m DcrCash) TransInfo(parm interface{}) ([]byte, error) {
+	pjs := parm.(*simplejson.Json)
+	startH := pjs.Get("starth").MustUint64()
+	endH := pjs.Get("endh").MustUint64()
+
+	if startH < 1 {
+		LOG("DEBUG", " input para  err:%v", startH)
+		startH = 1
+	}
+
+	//get longest block count
+	blockcount, err := CoinApi.WalleGetBlockCount()
+	if err != nil {
+		LOG("ERROR", " WalleGetBlockCount  err:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETCLOCKCOUNT_ERR, getErrMsg(GETCLOCKCOUNT_ERR, nil))
+	}
+
+	//get startblock hash by height
+
+	if startH > blockcount {
+		LOG("DEBUG", " startheight:%v >  blockcount:%v", startH, blockcount)
+		startH = blockcount
+	}
+
+	startblockhash, err := CoinApi.WalletGetBlockHash(uint64(startH - 1))
+	if err != nil {
+		LOG("ERROR", " WalletGetBlockHash startH:%v err:%v", startH, err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETBLOCKINFO_ERR, getErrMsg(GETBLOCKINFO_ERR, nil))
+	}
+
+	//get endblock time by height
+	if endH > blockcount {
+		LOG("DEBUG", " endheight:%v >  blockcount:%v", endH, blockcount)
+		endH = blockcount
+	}
+
+	endblockhash, err := CoinApi.WalletGetBlockHash(uint64(endH))
+	if err != nil {
+		LOG("ERROR", " WalletGetBlockHash startH:%v err:%v", startH, err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETBLOCKINFO_ERR, getErrMsg(GETBLOCKINFO_ERR, nil))
+	}
+
+	endblocktime, err := CoinApi.WalletGetBlockTime(endblockhash)
+	if err != nil {
+		LOG("ERROR", " WalletGetBlockTime endH:%v err:%v", endH, err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETBLOCKINFO_ERR, getErrMsg(GETBLOCKINFO_ERR, nil))
+	}
+
+	//Get all transactions in blocks since block [blockhash]
+	resp, err := CoinApi.WalleListSinceBlock(startblockhash)
+	if err != nil {
+		LOG("ERROR", " WalleListSinceBlock err:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, TRANSINFO_ERR, getErrMsg(TRANSINFO_ERR, nil))
+	}
+
+	var litelisttransactionsinfo []Listtransactions
+
+	if err = json.Unmarshal([]byte(resp), &litelisttransactionsinfo); err != nil {
+		LOG("ERROR", " inner json error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+	}
+
+	outputsArr := make([]map[string]interface{}, 0)
+	fmt.Println("WalleListSinceBlock_num:", len(litelisttransactionsinfo))
+	for index, listtransaction := range litelisttransactionsinfo {
+
+		// get all transactions from block startHright to endHeight
+		fmt.Println("BLockTime,Endblocktime", listtransaction.Blocktime, endblocktime, index)
+		if listtransaction.Blocktime <= endblocktime {
+			requestData := make(map[string]interface{})
+			confirmationheight, err := CoinApi.WalletGetBlockHeight(listtransaction.Blockhash)
+			if err != nil {
+				LOG("ERROR", "WalletGetBlockHeight error:%v", err.Error())
+				continue
+			}
+			requestData["confirmationheight"] = confirmationheight
+			requestData["address"] = listtransaction.Address
+			requestData["confirmationtimestamp"] = listtransaction.Timereceived
+			requestData["value"] = listtransaction.Amount
+			requestData["transactionid"] = listtransaction.Txid
+			requestData["confirmations"] = listtransaction.Confirmations
+			requestData["walletaddress"] = true
+			requestData["vout"] = listtransaction.Vout
+			outputsArr = append(outputsArr, requestData)
+		}
+	}
+
+	var jbuf []byte
+	resptmp := make(map[string]interface{})
+	resptmp["errcode"] = 0
+	resptmp["cointype"] = "DCR"
+	resptmp["outputs"] = outputsArr
+
+	if jbuf, err = json.Marshal(resptmp); err != nil {
+		LOG("ERROR", " inner json error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+	}
+	return jbuf, nil
+}
+
+func (m DcrCash) ListUnspent(parm interface{}) ([]byte, error) {
+	pjs := parm.(*simplejson.Json)
+	address, err := pjs.Get("address").StringArray()
+	if err != nil {
+		LOG("ERROR", "  input parm error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, LISTUNSPENT_ERR, getErrMsg(LISTUNSPENT_ERR, nil))
+	}
+	unspent, err := CoinApi.Listunspent(address)
+	if err != nil {
+		LOG("ERROR", "  get listunspent:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, LISTUNSPENT_ERR, getErrMsg(LISTUNSPENT_ERR, nil))
+	}
+
+	var jbuf []byte
+	resptmp := make(map[string]interface{})
+	resptmp["errcode"] = 0
+	resptmp["cointype"] = "DCR"
+	resptmp["unspents"] = unspent
+
+	if jbuf, err = json.Marshal(resptmp); err != nil {
+		LOG("ERROR", " inner json error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+	}
+	return jbuf, nil
+}
+
+func (m DcrCash) SendRawTransaction(parm interface{}) ([]byte, error) {
+	pjs := parm.(*simplejson.Json)
+	transdata := pjs.Get("data").MustString()
+
+	if len(transdata) == 0 {
+		return nil, fmt.Errorf(`{"cointype":"DCR","errcode":%v,"msg":"%v"}`, PARM_ERR, getErrMsg(PARM_ERR, []byte("hexstring is null")))
+	}
+	transactionhex, err := CoinApi.SendRawTransaction(transdata)
+	if err != nil {
+		LOG("ERROR", " SendRawTransaction err:%s", err.Error())
+		return nil, fmt.Errorf(`{"cointype":"DCR","errcode":%v,"msg":"%s"}`, SEND_RAW_TRANSACTION_ERR, getErrMsg(SEND_RAW_TRANSACTION_ERR, nil))
+	}
+
+	var jbuf []byte
+	resp := make(map[string]interface{})
+	resp["cointype"] = "DCR"
+	resp["transactionids"] = transactionhex
+	resp["errcode"] = 0
+	resp["msg"] = "OK"
+
+	if jbuf, err = json.Marshal(resp); err != nil {
+		LOG("ERROR", "inner json error:%v", err.Error())
+		return nil, fmt.Errorf(`{"cointype":"DCR","errcode":%v,"msg":"%s"}`, INNER_ERR, getErrMsg(INNER_ERR, nil))
+	}
+	return jbuf, nil
+}
+func (m DcrCash) ChainHeight(parm interface{}) ([]byte, error) {
+
+	blockcount, err := CoinApi.WalleGetBlockCount()
+	if err != nil {
+		LOG("ERROR", "  get current block count error:%v", err.Error())
+		return nil, fmt.Errorf(`{"errcode":%v,"mesage":"%s"}`, GETCLOCKCOUNT_ERR, getErrMsg(GETCLOCKCOUNT_ERR, nil))
+	}
+
+	sendstr := fmt.Sprintf(`{"errcode":%v,"height":%v}`, OK, blockcount)
+	return []byte(sendstr), nil
+}
+
+func init() {
+
+	Register(NameCoin, &DcrCash{})
+}

+ 48 - 0
src/dcrcash/dcrcashconfig.go

@@ -0,0 +1,48 @@
+package dcrcash
+
+import (
+	"fmt"
+	"runtime"
+	"strings"
+	"time"
+)
+
+type config struct {
+	Title      string
+	WalletInfo walletinfo   `toml:walletinfo`
+	Limit      limit        `toml:limit`
+	Rpc        rpc          `toml:rpc`
+	Walletpass walletpasswd `toml:walletpass`
+}
+
+type limit struct {
+	Fee string
+}
+
+type walletpasswd struct {
+	Passphrase string
+}
+type rpc struct {
+	Rpcuser     string
+	Rpcpassword string
+	Rpchost     string
+	Rpcport     int
+}
+
+type walletinfo struct {
+	WalletKey string
+}
+
+func LOG(info string, format string, v ...interface{}) {
+
+	_, file, line, _ := runtime.Caller(1)
+	fpaths := strings.Split(file, "/")
+	size := len(fpaths)
+	var sysflag = "dcrcash package"
+	if format == "" {
+		fmt.Printf("%v |%v|%v|%v()|%v|%v\n", time.Now().Format("2006-01-02 15:04:05"), info, sysflag, fpaths[size-1], line, fmt.Sprintln(v...))
+	} else {
+		fmt.Printf("%v|%v|%v|%v|%v|%v\n", time.Now().Format("2006-01-02 15:04:05"), info, sysflag, fpaths[size-1], line, fmt.Sprintf(format, v...))
+	}
+
+}

+ 57 - 0
src/dcrcash/dcrcasherr.go

@@ -0,0 +1,57 @@
+package dcrcash
+
+//"fmt"
+
+var (
+	ErrMsg map[int]string
+)
+
+const (
+	OK       = 0
+	TIME_OUT = iota + 20
+	WALLETINFO_ERR
+	INNER_ERR
+	TRANSINFO_ERR
+	AMOUNT_ERR
+	SENDCOINS_ERR
+	GETBALANCE_ERR
+	GETUNCONFIRMEDBALANCE_ERR
+	GETNEWADDRESS_ERR
+	DUMPPRIVKEY_ERR
+	GETCLOCKCOUNT_ERR
+	GETBLOCKINFO_ERR
+	LISTUNSPENT_ERR
+	SEND_RAW_TRANSACTION_ERR
+	PARM_ERR
+	INSUFFICIENT_FUNDS_TRANSACTION_ERR
+	UNKNOWN_ERR
+)
+
+func initDcrError() {
+	ErrMsg = make(map[int]string)
+	ErrMsg[0] = "成功"
+	ErrMsg[22] = " 钱包信息查询错误"
+	ErrMsg[23] = " 内部错误"
+	ErrMsg[24] = " 获取交易信息出错"
+	ErrMsg[25] = " 传入的转账金额不合法"
+	ErrMsg[26] = " 发送数字币出错"
+	ErrMsg[27] = " 获取已确认余额出错"
+	ErrMsg[28] = " 获取未确认的余额出错"
+	ErrMsg[29] = " 获取地址出错"
+	ErrMsg[30] = " 获取私钥出错"
+	ErrMsg[31] = " 获取当前区块链的高度出错"
+	ErrMsg[32] = " 获取区块链信息出错"
+	ErrMsg[33] = " 获取未使用的交易输出失败"
+	ErrMsg[34] = " 发送原始交易信息出错"
+	ErrMsg[35] = " 传入参数错误"
+	ErrMsg[36] = " 交易的资金不足"
+
+}
+
+func getErrMsg(ret int, data []byte) string {
+	msg, ok := ErrMsg[ret]
+	if ok {
+		return msg
+	}
+	return string(data)
+}

+ 211 - 0
src/dcrcash/type.go

@@ -0,0 +1,211 @@
+package dcrcash
+
+//  rpc  error struct
+type RpcError struct {
+	Code    int    `json:"code"`
+	Message string `json:"message"`
+}
+
+//get wallet info result struct
+type OutwalletInfo struct {
+	daemonconnected  bool
+	unlocked         bool
+	txfee            float64
+	ticketfee        float64
+	ticketpurchasing bool
+	votebits         uint64
+	votebitsextended string
+	voteversion      uint64
+	voting           bool
+}
+
+//  rpc  common result struct
+type RpcResult struct {
+	Result string   `json:"result"`
+	Error  RpcError `json:"error"`
+	Id     int      `json:"id"`
+}
+
+//set fee
+type Setfeeresult struct {
+	Result bool     `json:"result"`
+	Error  RpcError `json:"error"`
+	Id     int
+}
+
+type WalletinfoResult struct {
+	Result OutwalletInfo `json:"result"`
+	Error  RpcError      `json:"error"`
+	Id     int           `json:"id"`
+}
+
+//get block count
+type Blockcountresult struct {
+	Result uint64   `json:"result"`
+	Error  RpcError `json:"error"`
+	Id     int
+}
+
+type account struct {
+	AccountName             string  `json:"accountname"`
+	ImmatureCoinbaseRewards float64 `json:"immaturecoinbaserewards"`
+	ImmatureStakeGeneration float64 `json:"immaturestakegeneration"`
+	LockedByTickets         float64 `json:"lockedbytickets"`
+	Spendable               float64 `json:"spendable"`
+	Total                   float64 `json:"total"`
+	Unconfirmed             float64 `json:"unconfirmed"`
+	VotingAuthority         float64 `json:"votingauthority"`
+}
+type Accounts struct {
+	Balances  []account `json:"balances"`
+	Blockhash string    `json:"blockhash"`
+}
+
+//get Balance result struct
+type BalanceResult struct {
+	Result Accounts `json:"result"`
+	Error  RpcError `json:"error"`
+	Id     int      `json:"id"`
+}
+
+type Listtransactionsresult struct {
+	Result listtransactions `json:"result"`
+	Error  RpcError         `json:"error"`
+	Id     int              `json:"id"`
+}
+
+// list  transactions since blockhash result struct
+type Listtransactions struct {
+	Account           string   `json:"account"`
+	Address           string   `json:"address"`
+	Amount            float64  `json:"amount"`
+	Blockhash         string   `json:"blockhash"`
+	Blockindex        uint64   `json:"blockindex"`
+	Blocktime         uint64   `json:"blocktime"`
+	Category          string   `json:"category"`
+	Confirmations     uint64   `json:"confirmations"`
+	Fee               float64  `json:"fee"`
+	Generated         bool     `json:generated`
+	Involveswatchonly bool     `json:"involveswatchonly"`
+	Time              uint64   `json:"time"`
+	Timereceived      uint64   `json:"timereceived"`
+	Txid              string   `json:"txid"`
+	Txtype            string   `json:"txtype"`
+	Vout              uint64   `json:"vout"`
+	WalletConflicts   []string `json:"walletconflicts"`
+	Comment           string   `json:"comment"`
+	Otheraccount      string   `json:"otheraccount"`
+}
+
+type listtransactions struct {
+	Transactions []Listtransactions `json: "transactions"`
+	Lastblock    string             `json: "lastblock"`
+}
+
+type scriptsig struct {
+	Asm string
+	Hex string
+}
+
+type scriptpubkey struct {
+	Asm       string
+	Hex       string
+	ReqSigs   uint64
+	Type      string
+	Addresses []string
+	Commitamt float64
+}
+
+type vin struct {
+	Coinbase    string
+	Stakebase   string
+	Txid        string
+	vout        uint64
+	Tree        uint64
+	Sequese     uint64
+	Amountin    float64
+	Blockheighe uint64
+	Blockindex  uint64
+	ScriptSig   scriptsig
+}
+
+type vout struct {
+	Value        float64
+	N            uint64
+	Version      uint64
+	ScriptPubkey scriptpubkey
+}
+
+type rawtx struct {
+	Hex           string
+	Txid          string
+	Version       uint64
+	Locktime      uint64
+	Expiry        uint64
+	Vin           []vin
+	Vout          []vout
+	blockhash     string
+	blockheight   uint64
+	blockindex    uint64
+	tonfirmations uint64
+	time          uint64
+	blocktime     uint64
+}
+
+// get block info result struct
+type BlockInfo struct {
+	Hash              string
+	Confirmations     uint64
+	Size              uint64
+	Height            uint64
+	Version           uint64
+	Merkleroot        string
+	Stakerroot        string
+	Tx                []string
+	Rawtx             []rawtx
+	Stx               []string
+	Rawstx            []rawtx
+	Time              uint64
+	Nonce             uint64
+	Votebits          uint64
+	Finalstate        string
+	Voters            uint64
+	Freshstake        uint64
+	Revocations       uint64
+	Poolsize          uint64
+	Bits              string
+	Sbits             float64
+	Difficulty        float64
+	Extradata         string
+	Stakeversion      uint64
+	Previousblockhash string
+	Nextblockhash     string
+}
+
+type BlockResult struct {
+	Result BlockInfo `json:"result"`
+	Error  RpcError  `json:"error"`
+	Id     int       `json:"id"`
+}
+
+//list unspent info result struct
+type UnspentInfo struct {
+	Txid          string  `json:"txid"`
+	Vout          uint64  `json:"vout"`
+	Tree          uint64  `json:"tree"`
+	Txtype        uint64  `json:"txtype"`
+	Address       string  `json:"address"`
+	Account       string  `json:"account"`
+	ScriptPubKey  string  `json:"scriptpubkey"`
+	RedeemScript  string  `json:"redeemscript"`
+	Amount        float64 `json:"amount"`
+	Confirmations uint64  `json:"confirmations"`
+	Spendable     bool    `json:"spendable"`
+}
+
+//  RpcUnspentResult struct
+type RpcUnspentResult struct {
+	Result []UnspentInfo `json:"result"`
+	Error  RpcError      `json:"error"`
+	Id     int           `json:"id"`
+}

+ 5 - 6
src/github.com/piotrnar/gocoin/lib/btc/ecdsa.go

@@ -11,21 +11,20 @@ import (
 
 var (
 	EcdsaVerifyCnt uint64
-	EC_Verify func(k, s, h []byte) bool
+	EC_Verify      func(k, s, h []byte) bool
 )
 
 func EcdsaVerify(kd []byte, sd []byte, hash []byte) bool {
 	atomic.AddUint64(&EcdsaVerifyCnt, 1)
-	if len(kd)==0 || len(sd)==0 {
+	if len(kd) == 0 || len(sd) == 0 {
 		return false
 	}
-	if EC_Verify!=nil {
+	if EC_Verify != nil {
 		return EC_Verify(kd, sd, hash)
 	}
 	return secp256k1.Verify(kd, sd, hash)
 }
 
-
 func EcdsaSign(priv, hash []byte) (r, s *big.Int, err error) {
 	var sig secp256k1.Signature
 	var sec, msg, nonce secp256k1.Number
@@ -41,12 +40,12 @@ func EcdsaSign(priv, hash []byte) (r, s *big.Int, err error) {
 		rand.Read(buf[:])
 		sha.Write(buf[:])
 		nonce.SetBytes(sha.Sum(nil))
-		if nonce.Sign()>0 && nonce.Cmp(&secp256k1.TheCurve.Order.Int)<0 {
+		if nonce.Sign() > 0 && nonce.Cmp(&secp256k1.TheCurve.Order.Int) < 0 {
 			break
 		}
 	}
 
-	if sig.Sign(&sec, &msg, &nonce, nil)!=1 {
+	if sig.Sign(&sec, &msg, &nonce, nil) != 1 {
 		err = errors.New("ESCDS Sign error()")
 	}
 	return &sig.R.Int, &sig.S.Int, nil

+ 3 - 6
src/github.com/piotrnar/gocoin/lib/btc/key.go

@@ -18,20 +18,19 @@ type Signature struct {
 func NewPublicKey(buf []byte) (res *PublicKey, e error) {
 	res = new(PublicKey)
 	if !res.XY.ParsePubkey(buf) {
-		e = errors.New("NewPublicKey: Unknown format: "+hex.EncodeToString(buf[:]))
+		e = errors.New("NewPublicKey: Unknown format: " + hex.EncodeToString(buf[:]))
 		res = nil
 	}
 	return
 }
 
-
 func NewSignature(buf []byte) (*Signature, error) {
 	sig := new(Signature)
 	le := sig.ParseBytes(buf)
 	if le < 0 {
 		return nil, errors.New("NewSignature: ParseBytes error")
 	}
-	if le<len(buf) {
+	if le < len(buf) {
 		sig.HashType = buf[len(buf)-1]
 	}
 	return sig, nil
@@ -46,12 +45,10 @@ func (sig *Signature) RecoverPublicKey(msg []byte, recid int) (key *PublicKey) {
 	return
 }
 
-
 func (sig *Signature) IsLowS() bool {
-	return sig.S.Cmp(&secp256k1.TheCurve.HalfOrder.Int)<1
+	return sig.S.Cmp(&secp256k1.TheCurve.HalfOrder.Int) < 1
 }
 
-
 // Returns serialized canoncal signature followed by a hash type
 func (sig *Signature) Bytes() []byte {
 	return append(sig.Signature.Bytes(), sig.HashType)

+ 2 - 1
src/lite/litecoins.go

@@ -305,7 +305,8 @@ func (m Lite) ChainHeight(parm interface{}) ([]byte, error) {
 	sendstr := fmt.Sprintf(`{"errcode":%v,"height":%v}`, OK, blockcount)
 	return []byte(sendstr), nil
 }
-//add by hyb 
+
+//add by hyb
 func (m Lite) ListUnspent(parm interface{}) ([]byte, error) {
 	return nil, nil
 }

+ 1 - 1
src/zcash/zcash.go

@@ -27,7 +27,7 @@ type zcashResult struct {
 type zcashtaddrlistResult struct {
 	Result []string   `json:"result"`
 	Error  zcashError `json:"error"`
-	Id     string     `json:"id"`
+	Id     string     `json:"id"`  
 }
 
 //zcash rpc  get t-address  Balance result struct

+ 4 - 3
taskprocess.go

@@ -1,14 +1,15 @@
 package main
 
 import (
+	_ "bitcoin"
+	_ "bucash"
+	_ "dcrcash"
 	"errors"
 	"fmt"
+	_ "lite"
 	"template"
 	"time"
 	_ "zcash"
-	_ "lite"
-	_ "bucash"
-	_ "bitcoin"
 )
 
 func coinStart() {