Commit e4481593 authored by sanghg's avatar sanghg Committed by vipwzw

修复隐私合约中golint的警告

修改crypto、executor中的golint警告
parent f08844a1
...@@ -13,19 +13,19 @@ import ( ...@@ -13,19 +13,19 @@ import (
privacytypes "github.com/33cn/plugin/plugin/dapp/privacy/types" privacytypes "github.com/33cn/plugin/plugin/dapp/privacy/types"
) )
type OneTimeEd25519 struct{} type oneTimeEd25519 struct{}
func init() { func init() {
crypto.Register(privacytypes.SignNameOnetimeED25519, &OneTimeEd25519{}) crypto.Register(privacytypes.SignNameOnetimeED25519, &oneTimeEd25519{})
} }
func (onetime *OneTimeEd25519) GenKey() (crypto.PrivKey, error) { func (onetime *oneTimeEd25519) GenKey() (crypto.PrivKey, error) {
privKeyPrivacyPtr := &PrivKeyPrivacy{} privKeyPrivacyPtr := &PrivKeyPrivacy{}
pubKeyPrivacyPtr := &PubKeyPrivacy{} pubKeyPrivacyPtr := &PubKeyPrivacy{}
copy(privKeyPrivacyPtr[:PrivateKeyLen], crypto.CRandBytes(PrivateKeyLen)) copy(privKeyPrivacyPtr[:privateKeyLen], crypto.CRandBytes(privateKeyLen))
addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyPrivacyPtr)) addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyPrivacyPtr))
addr64 := (*[PrivateKeyLen]byte)(unsafe.Pointer(privKeyPrivacyPtr)) addr64 := (*[privateKeyLen]byte)(unsafe.Pointer(privKeyPrivacyPtr))
edwards25519.ScReduce(addr32, addr64) edwards25519.ScReduce(addr32, addr64)
//to generate the publickey //to generate the publickey
...@@ -38,16 +38,16 @@ func (onetime *OneTimeEd25519) GenKey() (crypto.PrivKey, error) { ...@@ -38,16 +38,16 @@ func (onetime *OneTimeEd25519) GenKey() (crypto.PrivKey, error) {
return *privKeyPrivacyPtr, nil return *privKeyPrivacyPtr, nil
} }
func (onetime *OneTimeEd25519) PrivKeyFromBytes(b []byte) (privKey crypto.PrivKey, err error) { func (onetime *oneTimeEd25519) PrivKeyFromBytes(b []byte) (privKey crypto.PrivKey, err error) {
if len(b) != 64 { if len(b) != 64 {
return nil, errors.New("invalid priv key byte") return nil, errors.New("invalid priv key byte")
} }
privKeyBytes := new([PrivateKeyLen]byte) privKeyBytes := new([privateKeyLen]byte)
pubKeyBytes := new([PublicKeyLen]byte) pubKeyBytes := new([publicKeyLen]byte)
copy(privKeyBytes[:KeyLen32], b[:KeyLen32]) copy(privKeyBytes[:KeyLen32], b[:KeyLen32])
addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyBytes)) addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyBytes))
addr64 := (*[PrivateKeyLen]byte)(unsafe.Pointer(privKeyBytes)) addr64 := (*[privateKeyLen]byte)(unsafe.Pointer(privKeyBytes))
//to generate the publickey //to generate the publickey
var A edwards25519.ExtendedGroupElement var A edwards25519.ExtendedGroupElement
...@@ -59,7 +59,7 @@ func (onetime *OneTimeEd25519) PrivKeyFromBytes(b []byte) (privKey crypto.PrivKe ...@@ -59,7 +59,7 @@ func (onetime *OneTimeEd25519) PrivKeyFromBytes(b []byte) (privKey crypto.PrivKe
return PrivKeyPrivacy(*privKeyBytes), nil return PrivKeyPrivacy(*privKeyBytes), nil
} }
func (onetime *OneTimeEd25519) PubKeyFromBytes(b []byte) (pubKey crypto.PubKey, err error) { func (onetime *oneTimeEd25519) PubKeyFromBytes(b []byte) (pubKey crypto.PubKey, err error) {
if len(b) != 32 { if len(b) != 32 {
return nil, errors.New("invalid pub key byte") return nil, errors.New("invalid pub key byte")
} }
...@@ -68,7 +68,7 @@ func (onetime *OneTimeEd25519) PubKeyFromBytes(b []byte) (pubKey crypto.PubKey, ...@@ -68,7 +68,7 @@ func (onetime *OneTimeEd25519) PubKeyFromBytes(b []byte) (pubKey crypto.PubKey,
return PubKeyPrivacy(*pubKeyBytes), nil return PubKeyPrivacy(*pubKeyBytes), nil
} }
func (onetime *OneTimeEd25519) SignatureFromBytes(b []byte) (sig crypto.Signature, err error) { func (onetime *oneTimeEd25519) SignatureFromBytes(b []byte) (sig crypto.Signature, err error) {
sigBytes := new([64]byte) sigBytes := new([64]byte)
copy(sigBytes[:], b[:]) copy(sigBytes[:], b[:])
return SignatureOnetime(*sigBytes), nil return SignatureOnetime(*sigBytes), nil
......
...@@ -11,7 +11,7 @@ import ( ...@@ -11,7 +11,7 @@ import (
"unsafe" "unsafe"
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
. "github.com/33cn/chain33/common/crypto" "github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/common/crypto/sha3" "github.com/33cn/chain33/common/crypto/sha3"
"github.com/33cn/chain33/common/ed25519/edwards25519" "github.com/33cn/chain33/common/ed25519/edwards25519"
log "github.com/33cn/chain33/common/log/log15" log "github.com/33cn/chain33/common/log/log15"
...@@ -22,11 +22,13 @@ import ( ...@@ -22,11 +22,13 @@ import (
) )
const ( const (
PublicKeyLen = 32 publicKeyLen = 32
PrivateKeyLen = 64 privateKeyLen = 64
KeyLen32 = 32 // KeyLen32 key Length
KeyLen32 = 32
) )
// Privacy privacy struct type
type Privacy struct { type Privacy struct {
ViewPubkey PubKeyPrivacy ViewPubkey PubKeyPrivacy
ViewPrivKey PrivKeyPrivacy ViewPrivKey PrivKeyPrivacy
...@@ -34,28 +36,32 @@ type Privacy struct { ...@@ -34,28 +36,32 @@ type Privacy struct {
SpendPrivKey PrivKeyPrivacy SpendPrivKey PrivKeyPrivacy
} }
type EllipticCurvePoint [32]byte type ellipticCurvePoint [32]byte
type sigcomm struct { type sigcomm struct {
hash [32]byte hash [32]byte
pubkey EllipticCurvePoint pubkey ellipticCurvePoint
comm EllipticCurvePoint comm ellipticCurvePoint
} }
// //
type sigcommArray [32 * 3]byte type sigcommArray [32 * 3]byte
// KeyImage key image type
type KeyImage [32]byte type KeyImage [32]byte
var ( var (
ErrViewPub = errors.New("ErrViewPub") errViewPub = errors.New("ErrViewPub")
ErrSpendPub = errors.New("ErrSpendPub") errSpendPub = errors.New("ErrSpendPub")
ErrViewSecret = errors.New("ErrViewSecret") errViewSecret = errors.New("ErrViewSecret")
ErrSpendSecret = errors.New("ErrSpendSecret") errSpendSecret = errors.New("ErrSpendSecret")
ErrNullRandInput = errors.New("ErrNullRandInput") errNullRandInput = errors.New("ErrNullRandInput")
) )
var privacylog = log.New("module", "crypto.privacy") var privacylog = log.New("module", "crypto.privacy")
////////////// //////////////
// NewPrivacy create privacy object
func NewPrivacy() *Privacy { func NewPrivacy() *Privacy {
privacy := &Privacy{} privacy := &Privacy{}
GenerateKeyPair(&privacy.SpendPrivKey, &privacy.SpendPubkey) GenerateKeyPair(&privacy.SpendPrivKey, &privacy.SpendPubkey)
...@@ -64,6 +70,7 @@ func NewPrivacy() *Privacy { ...@@ -64,6 +70,7 @@ func NewPrivacy() *Privacy {
return privacy return privacy
} }
// NewPrivacyWithPrivKey create privacy from private key
func NewPrivacyWithPrivKey(privKey *[KeyLen32]byte) (privacy *Privacy, err error) { func NewPrivacyWithPrivKey(privKey *[KeyLen32]byte) (privacy *Privacy, err error) {
privacylog.Info("NewPrivacyWithPrivKey", "input prikey", common.Bytes2Hex(privKey[:])) privacylog.Info("NewPrivacyWithPrivKey", "input prikey", common.Bytes2Hex(privKey[:]))
hash := sccrypto.HashAll(*privKey) hash := sccrypto.HashAll(*privKey)
...@@ -83,19 +90,19 @@ func NewPrivacyWithPrivKey(privKey *[KeyLen32]byte) (privacy *Privacy, err error ...@@ -83,19 +90,19 @@ func NewPrivacyWithPrivKey(privKey *[KeyLen32]byte) (privacy *Privacy, err error
return privacy, nil return privacy, nil
} }
//(A, B) => Hs(rA)G + B, rG=>R //GenerateOneTimeAddr (A, B) => Hs(rA)G + B, rG=>R
//func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int64) (pubkeyOnetime, RtxPublicKey *[32]byte, errInfo error) { //func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int64) (pubkeyOnetime, RtxPublicKey *[32]byte, errInfo error) {
func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int64) (pubkeyOnetime *[32]byte, errInfo error) { func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int64) (pubkeyOnetime *[32]byte, errInfo error) {
//to calculate rA //to calculate rA
var point edwards25519.ExtendedGroupElement var point edwards25519.ExtendedGroupElement
if res := point.FromBytes(viewPub); !res { if res := point.FromBytes(viewPub); !res {
return nil, ErrViewPub return nil, errViewPub
} }
//skAddr32 := (*[KeyLen32]byte)(unsafe.Pointer(sk)) //skAddr32 := (*[KeyLen32]byte)(unsafe.Pointer(sk))
if !edwards25519.ScCheck(skAddr32) { if !edwards25519.ScCheck(skAddr32) {
privacylog.Error("xxx GenerateOneTimeAddr Fail to do edwards25519.ScCheck with sk \n") privacylog.Error("xxx GenerateOneTimeAddr Fail to do edwards25519.ScCheck with sk \n")
return nil, ErrViewSecret return nil, errViewSecret
} }
var point2 edwards25519.ProjectiveGroupElement var point2 edwards25519.ProjectiveGroupElement
zeroValue := &[32]byte{} zeroValue := &[32]byte{}
...@@ -110,13 +117,13 @@ func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int6 ...@@ -110,13 +117,13 @@ func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int6
//to calculate Hs(rA)G + B //to calculate Hs(rA)G + B
var B edwards25519.ExtendedGroupElement //A var B edwards25519.ExtendedGroupElement //A
if res := B.FromBytes(spendPub); !res { if res := B.FromBytes(spendPub); !res {
return nil, ErrSpendPub return nil, errSpendPub
} }
//Hs(rA) //Hs(rA)
Hs_rA := derivation2scalar(rA, outputIndex) HsRA := derivation2scalar(rA, outputIndex)
var A edwards25519.ExtendedGroupElement var A edwards25519.ExtendedGroupElement
edwards25519.GeScalarMultBase(&A, Hs_rA) edwards25519.GeScalarMultBase(&A, HsRA)
//A.ToBytes(publicKey) //A.ToBytes(publicKey)
var cachedA edwards25519.CachedGroupElement var cachedA edwards25519.CachedGroupElement
//Hs(rA)G //Hs(rA)G
...@@ -133,8 +140,8 @@ func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int6 ...@@ -133,8 +140,8 @@ func GenerateOneTimeAddr(viewPub, spendPub, skAddr32 *[32]byte, outputIndex int6
return return
} }
//calculate Hs(aR) + b //RecoverOnetimePriKey calculate Hs(aR) + b
func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey PrivKey, outputIndex int64) (PrivKey, error) { func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey crypto.PrivKey, outputIndex int64) (crypto.PrivKey, error) {
var viewSecAddr, spendSecAddr, RtxPubAddr *[32]byte var viewSecAddr, spendSecAddr, RtxPubAddr *[32]byte
viewSecAddr = (*[32]byte)(unsafe.Pointer(&viewSecretKey.Bytes()[0])) viewSecAddr = (*[32]byte)(unsafe.Pointer(&viewSecretKey.Bytes()[0]))
spendSecAddr = (*[32]byte)(unsafe.Pointer(&spendSecretKey.Bytes()[0])) spendSecAddr = (*[32]byte)(unsafe.Pointer(&spendSecretKey.Bytes()[0]))
...@@ -143,12 +150,12 @@ func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey PrivKey, outpu ...@@ -143,12 +150,12 @@ func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey PrivKey, outpu
var point edwards25519.ExtendedGroupElement var point edwards25519.ExtendedGroupElement
if res := point.FromBytes(RtxPubAddr); !res { if res := point.FromBytes(RtxPubAddr); !res {
privacylog.Error("RecoverOnetimePriKey Fail to do get point.FromBytes with viewSecAddr \n") privacylog.Error("RecoverOnetimePriKey Fail to do get point.FromBytes with viewSecAddr \n")
return nil, ErrViewSecret return nil, errViewSecret
} }
if !edwards25519.ScCheck(viewSecAddr) { if !edwards25519.ScCheck(viewSecAddr) {
privacylog.Error("xxx RecoverOnetimePriKey Fail to do edwards25519.ScCheck with viewSecAddr \n") privacylog.Error("xxx RecoverOnetimePriKey Fail to do edwards25519.ScCheck with viewSecAddr \n")
return nil, ErrViewSecret return nil, errViewSecret
} }
var point2 edwards25519.ProjectiveGroupElement var point2 edwards25519.ProjectiveGroupElement
...@@ -163,21 +170,21 @@ func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey PrivKey, outpu ...@@ -163,21 +170,21 @@ func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey PrivKey, outpu
if !edwards25519.ScCheck(spendSecAddr) { if !edwards25519.ScCheck(spendSecAddr) {
privacylog.Error("xxx RecoverOnetimePriKey Fail to do edwards25519.ScCheck with spendSecAddr \n") privacylog.Error("xxx RecoverOnetimePriKey Fail to do edwards25519.ScCheck with spendSecAddr \n")
return nil, ErrViewSecret return nil, errViewSecret
} }
//2rd to calculate Hs(aR) + b //2rd to calculate Hs(aR) + b
//Hs(aR) //Hs(aR)
Hs_aR := derivation2scalar(aR, outputIndex) HsAR := derivation2scalar(aR, outputIndex)
//TODO:代码疑问 //TODO:代码疑问
//var onetimePriKey PrivKeyEd25519 //var onetimePriKey PrivKeyEd25519
//onetimePriKeyAddr := (*[32]byte)(unsafe.Pointer(&onetimePriKey.Bytes()[0])) //onetimePriKeyAddr := (*[32]byte)(unsafe.Pointer(&onetimePriKey.Bytes()[0]))
//edwards25519.ScAdd(onetimePriKeyAddr, Hs_aR, spendSecAddr) //edwards25519.ScAdd(onetimePriKeyAddr, HsAR, spendSecAddr)
onetimePriKeydata := new([64]byte) onetimePriKeydata := new([64]byte)
onetimePriKeyAddr := (*[32]byte)(unsafe.Pointer(onetimePriKeydata)) onetimePriKeyAddr := (*[32]byte)(unsafe.Pointer(onetimePriKeydata))
edwards25519.ScAdd(onetimePriKeyAddr, Hs_aR, spendSecAddr) edwards25519.ScAdd(onetimePriKeyAddr, HsAR, spendSecAddr)
prikey := PrivKeyPrivacy(*onetimePriKeydata) prikey := PrivKeyPrivacy(*onetimePriKeydata)
prikey.PubKey() prikey.PubKey()
...@@ -202,11 +209,12 @@ func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey PrivKey, outpu ...@@ -202,11 +209,12 @@ func RecoverOnetimePriKey(R []byte, viewSecretKey, spendSecretKey PrivKey, outpu
// return checkRes // return checkRes
//} //}
// GenerateKeyPair create key pair
func GenerateKeyPair(privKeyPrivacyPtr *PrivKeyPrivacy, pubKeyPrivacyPtr *PubKeyPrivacy) { func GenerateKeyPair(privKeyPrivacyPtr *PrivKeyPrivacy, pubKeyPrivacyPtr *PubKeyPrivacy) {
copy(privKeyPrivacyPtr[:PrivateKeyLen], CRandBytes(PrivateKeyLen)) copy(privKeyPrivacyPtr[:privateKeyLen], crypto.CRandBytes(privateKeyLen))
addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyPrivacyPtr)) addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyPrivacyPtr))
addr64 := (*[PrivateKeyLen]byte)(unsafe.Pointer(privKeyPrivacyPtr)) addr64 := (*[privateKeyLen]byte)(unsafe.Pointer(privKeyPrivacyPtr))
edwards25519.ScReduce(addr32, addr64) edwards25519.ScReduce(addr32, addr64)
//to generate the publickey //to generate the publickey
...@@ -219,7 +227,7 @@ func GenerateKeyPair(privKeyPrivacyPtr *PrivKeyPrivacy, pubKeyPrivacyPtr *PubKey ...@@ -219,7 +227,7 @@ func GenerateKeyPair(privKeyPrivacyPtr *PrivKeyPrivacy, pubKeyPrivacyPtr *PubKey
func generateKeyPairWithPrivKey(privByte *[KeyLen32]byte, privKeyPrivacyPtr *PrivKeyPrivacy, pubKeyPrivacyPtr *PubKeyPrivacy) error { func generateKeyPairWithPrivKey(privByte *[KeyLen32]byte, privKeyPrivacyPtr *PrivKeyPrivacy, pubKeyPrivacyPtr *PubKeyPrivacy) error {
if nil == privByte { if nil == privByte {
return ErrNullRandInput return errNullRandInput
} }
_, err := io.ReadFull(bytes.NewReader(privByte[:]), privKeyPrivacyPtr[:32]) _, err := io.ReadFull(bytes.NewReader(privByte[:]), privKeyPrivacyPtr[:32])
...@@ -228,7 +236,7 @@ func generateKeyPairWithPrivKey(privByte *[KeyLen32]byte, privKeyPrivacyPtr *Pri ...@@ -228,7 +236,7 @@ func generateKeyPairWithPrivKey(privByte *[KeyLen32]byte, privKeyPrivacyPtr *Pri
} }
addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyPrivacyPtr)) addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyPrivacyPtr))
addr64 := (*[PrivateKeyLen]byte)(unsafe.Pointer(privKeyPrivacyPtr)) addr64 := (*[privateKeyLen]byte)(unsafe.Pointer(privKeyPrivacyPtr))
edwards25519.ScReduce(addr32, addr64) edwards25519.ScReduce(addr32, addr64)
//to generate the publickey //to generate the publickey
...@@ -250,11 +258,11 @@ func mul8(r *edwards25519.CompletedGroupElement, t *edwards25519.ProjectiveGroup ...@@ -250,11 +258,11 @@ func mul8(r *edwards25519.CompletedGroupElement, t *edwards25519.ProjectiveGroup
u.Double(r) u.Double(r)
} }
func derivation2scalar(derivation_rA *[32]byte, outputIndex int64) (ellipticCurveScalar *[32]byte) { func derivation2scalar(derivationRA *[32]byte, outputIndex int64) (ellipticCurveScalar *[32]byte) {
len := 32 + (unsafe.Sizeof(outputIndex)*8+6)/7 len := 32 + (unsafe.Sizeof(outputIndex)*8+6)/7
//buf := new([len]byte) //buf := new([len]byte)
buf := make([]byte, len) buf := make([]byte, len)
copy(buf[:32], derivation_rA[:]) copy(buf[:32], derivationRA[:])
index := 32 index := 32
for outputIndex >= 0x80 { for outputIndex >= 0x80 {
buf[index] = byte((outputIndex & 0x7f) | 0x80) buf[index] = byte((outputIndex & 0x7f) | 0x80)
......
...@@ -73,7 +73,7 @@ func TestPrivacySignWithFixInput(t *testing.T) { ...@@ -73,7 +73,7 @@ func TestPrivacySignWithFixInput(t *testing.T) {
Signature: sig.Bytes(), Signature: sig.Bytes(),
} }
c := &OneTimeEd25519{} c := &oneTimeEd25519{}
pub, err := c.PubKeyFromBytes(sign.Pubkey) pub, err := c.PubKeyFromBytes(sign.Pubkey)
if err != nil { if err != nil {
...@@ -156,7 +156,7 @@ func TestPrivacySignWithFixInput(t *testing.T) { ...@@ -156,7 +156,7 @@ func TestPrivacySignWithFixInput(t *testing.T) {
// Signature:sig.Bytes(), // Signature:sig.Bytes(),
// } // }
// //
// c := &OneTimeEd25519{} // c := &oneTimeEd25519{}
// //
// pub, err := c.PubKeyFromBytes(sign.Pubkey) // pub, err := c.PubKeyFromBytes(sign.Pubkey)
// if err != nil { // if err != nil {
......
...@@ -8,22 +8,25 @@ import ( ...@@ -8,22 +8,25 @@ import (
"bytes" "bytes"
"unsafe" "unsafe"
. "github.com/33cn/chain33/common/crypto" "github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/common/crypto/sha3" "github.com/33cn/chain33/common/crypto/sha3"
"github.com/33cn/chain33/common/ed25519/edwards25519" "github.com/33cn/chain33/common/ed25519/edwards25519"
) )
type PrivKeyPrivacy [PrivateKeyLen]byte // PrivKeyPrivacy struct data type
type PrivKeyPrivacy [privateKeyLen]byte
// Bytes convert to bytes
func (privKey PrivKeyPrivacy) Bytes() []byte { func (privKey PrivKeyPrivacy) Bytes() []byte {
return privKey[:] return privKey[:]
} }
func (privKey PrivKeyPrivacy) Sign(msg []byte) Signature { // Sign signature trasaction
func (privKey PrivKeyPrivacy) Sign(msg []byte) crypto.Signature {
temp := new([64]byte) temp := new([64]byte)
randomScalar := new([32]byte) randomScalar := new([32]byte)
copy(temp[:], CRandBytes(64)) copy(temp[:], crypto.CRandBytes(64))
edwards25519.ScReduce(randomScalar, temp) edwards25519.ScReduce(randomScalar, temp)
var sigcommdata sigcommArray var sigcommdata sigcommArray
...@@ -47,12 +50,13 @@ func (privKey PrivKeyPrivacy) Sign(msg []byte) Signature { ...@@ -47,12 +50,13 @@ func (privKey PrivKeyPrivacy) Sign(msg []byte) Signature {
return sigOnetime return sigOnetime
} }
func (privKey PrivKeyPrivacy) PubKey() PubKey { // PubKey get public key
func (privKey PrivKeyPrivacy) PubKey() crypto.PubKey {
var pubKeyPrivacy PubKeyPrivacy var pubKeyPrivacy PubKeyPrivacy
addr32 := (*[KeyLen32]byte)(unsafe.Pointer(&privKey.Bytes()[0])) addr32 := (*[KeyLen32]byte)(unsafe.Pointer(&privKey.Bytes()[0]))
addr64 := (*[PrivateKeyLen]byte)(unsafe.Pointer(&privKey.Bytes()[0])) addr64 := (*[privateKeyLen]byte)(unsafe.Pointer(&privKey.Bytes()[0]))
var A edwards25519.ExtendedGroupElement var A edwards25519.ExtendedGroupElement
pubKeyAddr32 := (*[KeyLen32]byte)(unsafe.Pointer(&pubKeyPrivacy)) pubKeyAddr32 := (*[KeyLen32]byte)(unsafe.Pointer(&pubKeyPrivacy))
...@@ -63,10 +67,10 @@ func (privKey PrivKeyPrivacy) PubKey() PubKey { ...@@ -63,10 +67,10 @@ func (privKey PrivKeyPrivacy) PubKey() PubKey {
return pubKeyPrivacy return pubKeyPrivacy
} }
func (privKey PrivKeyPrivacy) Equals(other PrivKey) bool { // Equals check equals
func (privKey PrivKeyPrivacy) Equals(other crypto.PrivKey) bool {
if otherEd, ok := other.(PrivKeyPrivacy); ok { if otherEd, ok := other.(PrivKeyPrivacy); ok {
return bytes.Equal(privKey[:], otherEd[:]) return bytes.Equal(privKey[:], otherEd[:])
} else {
return false
} }
return false
} }
...@@ -9,24 +9,28 @@ import ( ...@@ -9,24 +9,28 @@ import (
"fmt" "fmt"
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
. "github.com/33cn/chain33/common/crypto" "github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
privacytypes "github.com/33cn/plugin/plugin/dapp/privacy/types" privacytypes "github.com/33cn/plugin/plugin/dapp/privacy/types"
) )
type PubKeyPrivacy [PublicKeyLen]byte // PubKeyPrivacy key struct types
type PubKeyPrivacy [publicKeyLen]byte
// Bytes convert to bytes
func (pubKey PubKeyPrivacy) Bytes() []byte { func (pubKey PubKeyPrivacy) Bytes() []byte {
return pubKey[:] return pubKey[:]
} }
// Bytes2PubKeyPrivacy convert bytes to PubKeyPrivacy
func Bytes2PubKeyPrivacy(in []byte) PubKeyPrivacy { func Bytes2PubKeyPrivacy(in []byte) PubKeyPrivacy {
var temp PubKeyPrivacy var temp PubKeyPrivacy
copy(temp[:], in) copy(temp[:], in)
return temp return temp
} }
func (pubKey PubKeyPrivacy) VerifyBytes(msg []byte, sig_ Signature) bool { // VerifyBytes verify bytes
func (pubKey PubKeyPrivacy) VerifyBytes(msg []byte, sig crypto.Signature) bool {
var tx types.Transaction var tx types.Transaction
if err := types.Decode(msg, &tx); err != nil { if err := types.Decode(msg, &tx); err != nil {
return false return false
...@@ -47,7 +51,7 @@ func (pubKey PubKeyPrivacy) VerifyBytes(msg []byte, sig_ Signature) bool { ...@@ -47,7 +51,7 @@ func (pubKey PubKeyPrivacy) VerifyBytes(msg []byte, sig_ Signature) bool {
return false return false
} }
var ringSign types.RingSignature var ringSign types.RingSignature
if err := types.Decode(sig_.Bytes(), &ringSign); err != nil { if err := types.Decode(sig.Bytes(), &ringSign); err != nil {
return false return false
} }
...@@ -99,14 +103,15 @@ func (pubKey PubKeyPrivacy) VerifyBytes(msg []byte, sig_ Signature) bool { ...@@ -99,14 +103,15 @@ func (pubKey PubKeyPrivacy) VerifyBytes(msg []byte, sig_ Signature) bool {
// return subtle.ConstantTimeCompare(sigAddr32a[:], out32[:]) == 1 // return subtle.ConstantTimeCompare(sigAddr32a[:], out32[:]) == 1
//} //}
// KeyString convert to string
func (pubKey PubKeyPrivacy) KeyString() string { func (pubKey PubKeyPrivacy) KeyString() string {
return fmt.Sprintf("%X", pubKey[:]) return fmt.Sprintf("%X", pubKey[:])
} }
func (pubKey PubKeyPrivacy) Equals(other PubKey) bool { // Equals check equals
func (pubKey PubKeyPrivacy) Equals(other crypto.PubKey) bool {
if otherEd, ok := other.(PubKeyPrivacy); ok { if otherEd, ok := other.(PubKeyPrivacy); ok {
return bytes.Equal(pubKey[:], otherEd[:]) return bytes.Equal(pubKey[:], otherEd[:])
} else {
return false
} }
return false
} }
...@@ -13,6 +13,7 @@ import ( ...@@ -13,6 +13,7 @@ import (
privacytypes "github.com/33cn/plugin/plugin/dapp/privacy/types" privacytypes "github.com/33cn/plugin/plugin/dapp/privacy/types"
) )
// Sign signature data struct type
type Sign [64]byte type Sign [64]byte
func randomScalar(res *[32]byte) { func randomScalar(res *[32]byte) {
...@@ -38,16 +39,16 @@ func generateKeyImage(pub *PubKeyPrivacy, sec *PrivKeyPrivacy, image *KeyImage) ...@@ -38,16 +39,16 @@ func generateKeyImage(pub *PubKeyPrivacy, sec *PrivKeyPrivacy, image *KeyImage)
func generateRingSignature(data []byte, image *KeyImage, pubs []*PubKeyPrivacy, sec *PrivKeyPrivacy, signs []*Sign, index int) error { func generateRingSignature(data []byte, image *KeyImage, pubs []*PubKeyPrivacy, sec *PrivKeyPrivacy, signs []*Sign, index int) error {
var sum, k, h, tmp [32]byte var sum, k, h, tmp [32]byte
var image_pre edwards25519.DsmPreCompGroupElement var imagePre edwards25519.DsmPreCompGroupElement
var image_unp edwards25519.ExtendedGroupElement var imageUnp edwards25519.ExtendedGroupElement
var buf []byte var buf []byte
buf = append(buf, data...) buf = append(buf, data...)
if !edwards25519.GeFromBytesVartime(&image_unp, (*[32]byte)(unsafe.Pointer(image))) { if !edwards25519.GeFromBytesVartime(&imageUnp, (*[32]byte)(unsafe.Pointer(image))) {
privacylog.Error("generateRingSignature", "from image failed.") privacylog.Error("generateRingSignature", "from image failed.")
return privacytypes.ErrGeFromBytesVartime return privacytypes.ErrGeFromBytesVartime
} }
edwards25519.GeDsmPrecomp(&image_pre, &image_unp) edwards25519.GeDsmPrecomp(&imagePre, &imageUnp)
for i := 0; i < len(pubs); i++ { for i := 0; i < len(pubs); i++ {
var tmp2 edwards25519.ProjectiveGroupElement var tmp2 edwards25519.ProjectiveGroupElement
var tmp3 edwards25519.ExtendedGroupElement var tmp3 edwards25519.ExtendedGroupElement
...@@ -93,7 +94,7 @@ func generateRingSignature(data []byte, image *KeyImage, pubs []*PubKeyPrivacy, ...@@ -93,7 +94,7 @@ func generateRingSignature(data []byte, image *KeyImage, pubs []*PubKeyPrivacy,
// r = a * A + b * B // r = a * A + b * B
// Wi * Hp(Pi) + q_i * I // Wi * Hp(Pi) + q_i * I
// (r, Wi, Hp(Pi), q_i, I) // (r, Wi, Hp(Pi), q_i, I)
edwards25519.GeDoubleScalarmultPrecompVartime(&tmp2, pb, &tmp3, pa, &image_pre) edwards25519.GeDoubleScalarmultPrecompVartime(&tmp2, pb, &tmp3, pa, &imagePre)
// save q_i*Hp(Pi) + Wi*I // save q_i*Hp(Pi) + Wi*I
tmp2.ToBytes(&tmp) tmp2.ToBytes(&tmp)
buf = append(buf, tmp[:]...) buf = append(buf, tmp[:]...)
...@@ -115,17 +116,17 @@ func generateRingSignature(data []byte, image *KeyImage, pubs []*PubKeyPrivacy, ...@@ -115,17 +116,17 @@ func generateRingSignature(data []byte, image *KeyImage, pubs []*PubKeyPrivacy,
return nil return nil
} }
func checkRingSignature(prefix_hash []byte, image *KeyImage, pubs []*PubKeyPrivacy, signs []*Sign) bool { func checkRingSignature(prefixHash []byte, image *KeyImage, pubs []*PubKeyPrivacy, signs []*Sign) bool {
var sum, h, tmp [32]byte var sum, h, tmp [32]byte
var image_unp edwards25519.ExtendedGroupElement var imageUnp edwards25519.ExtendedGroupElement
var image_pre edwards25519.DsmPreCompGroupElement var imagePre edwards25519.DsmPreCompGroupElement
var buf []byte var buf []byte
buf = append(buf, prefix_hash...) buf = append(buf, prefixHash...)
if !edwards25519.GeFromBytesVartime(&image_unp, (*[32]byte)(unsafe.Pointer(image))) { if !edwards25519.GeFromBytesVartime(&imageUnp, (*[32]byte)(unsafe.Pointer(image))) {
return false return false
} }
edwards25519.GeDsmPrecomp(&image_pre, &image_unp) edwards25519.GeDsmPrecomp(&imagePre, &imageUnp)
for i := 0; i < len(pubs); i++ { for i := 0; i < len(pubs); i++ {
var tmp2 edwards25519.ProjectiveGroupElement var tmp2 edwards25519.ProjectiveGroupElement
var tmp3 edwards25519.ExtendedGroupElement var tmp3 edwards25519.ExtendedGroupElement
...@@ -147,7 +148,7 @@ func checkRingSignature(prefix_hash []byte, image *KeyImage, pubs []*PubKeyPriva ...@@ -147,7 +148,7 @@ func checkRingSignature(prefix_hash []byte, image *KeyImage, pubs []*PubKeyPriva
//Hp(Pi) //Hp(Pi)
edwards25519.HashToEc(pub[:], &tmp3) edwards25519.HashToEc(pub[:], &tmp3)
//R'_i = r_i * Hp(Pi) + c_i * I //R'_i = r_i * Hp(Pi) + c_i * I
edwards25519.GeDoubleScalarmultPrecompVartime(&tmp2, pb, &tmp3, pa, &image_pre) edwards25519.GeDoubleScalarmultPrecompVartime(&tmp2, pb, &tmp3, pa, &imagePre)
//save: R'_i = r_i * Hp(Pi) + c_i * I //save: R'_i = r_i * Hp(Pi) + c_i * I
tmp2.ToBytes(&tmp) tmp2.ToBytes(&tmp)
buf = append(buf, tmp[:]...) buf = append(buf, tmp[:]...)
...@@ -161,6 +162,7 @@ func checkRingSignature(prefix_hash []byte, image *KeyImage, pubs []*PubKeyPriva ...@@ -161,6 +162,7 @@ func checkRingSignature(prefix_hash []byte, image *KeyImage, pubs []*PubKeyPriva
return edwards25519.ScIsNonZero(&h) == 0 return edwards25519.ScIsNonZero(&h) == 0
} }
// GenerateRingSignature create ring signature object
func GenerateRingSignature(datahash []byte, utxos []*privacytypes.UTXOBasic, privKey []byte, realUtxoIndex int, keyImage []byte) (*types.RingSignatureItem, error) { func GenerateRingSignature(datahash []byte, utxos []*privacytypes.UTXOBasic, privKey []byte, realUtxoIndex int, keyImage []byte) (*types.RingSignatureItem, error) {
count := len(utxos) count := len(utxos)
signs := make([]*Sign, count) signs := make([]*Sign, count)
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
/* /*
基于框架中Crypto接口,实现签名、验证的处理 基于框架中Crypto接口,实现签名、验证的处理
*/ */
package privacy package privacy
import ( import (
...@@ -28,18 +29,22 @@ type RingSignature struct { ...@@ -28,18 +29,22 @@ type RingSignature struct {
sign types.RingSignature sign types.RingSignature
} }
// Bytes convert to bytest
func (r *RingSignature) Bytes() []byte { func (r *RingSignature) Bytes() []byte {
return types.Encode(&r.sign) return types.Encode(&r.sign)
} }
// IsZero check is zero
func (r *RingSignature) IsZero() bool { func (r *RingSignature) IsZero() bool {
return len(r.sign.GetItems()) == 0 return len(r.sign.GetItems()) == 0
} }
// String convert to string
func (r *RingSignature) String() string { func (r *RingSignature) String() string {
return r.sign.String() return r.sign.String()
} }
// Equals check equals
func (r *RingSignature) Equals(other crypto.Signature) bool { func (r *RingSignature) Equals(other crypto.Signature) bool {
if _, ok := other.(*RingSignature); ok { if _, ok := other.(*RingSignature); ok {
this := types.Encode(&r.sign) this := types.Encode(&r.sign)
...@@ -50,13 +55,15 @@ func (r *RingSignature) Equals(other crypto.Signature) bool { ...@@ -50,13 +55,15 @@ func (r *RingSignature) Equals(other crypto.Signature) bool {
// RingSignPrivateKey 环签名中对于crypto.PrivKey接口实现 // RingSignPrivateKey 环签名中对于crypto.PrivKey接口实现
type RingSignPrivateKey struct { type RingSignPrivateKey struct {
key [PrivateKeyLen]byte key [privateKeyLen]byte
} }
// Bytes convert key to bytest
func (privkey *RingSignPrivateKey) Bytes() []byte { func (privkey *RingSignPrivateKey) Bytes() []byte {
return privkey.key[:] return privkey.key[:]
} }
// Sign signature trasaction
func (privkey *RingSignPrivateKey) Sign(msg []byte) crypto.Signature { func (privkey *RingSignPrivateKey) Sign(msg []byte) crypto.Signature {
emptySign := &RingSignature{} emptySign := &RingSignature{}
if len(msg) <= 0 { if len(msg) <= 0 {
...@@ -107,10 +114,11 @@ func (privkey *RingSignPrivateKey) Sign(msg []byte) crypto.Signature { ...@@ -107,10 +114,11 @@ func (privkey *RingSignPrivateKey) Sign(msg []byte) crypto.Signature {
return emptySign return emptySign
} }
// PubKey convert to public key
func (privkey *RingSignPrivateKey) PubKey() crypto.PubKey { func (privkey *RingSignPrivateKey) PubKey() crypto.PubKey {
publicKey := new(RingSignPublicKey) publicKey := new(RingSignPublicKey)
addr32 := (*[KeyLen32]byte)(unsafe.Pointer(&privkey.key)) addr32 := (*[KeyLen32]byte)(unsafe.Pointer(&privkey.key))
addr64 := (*[PrivateKeyLen]byte)(unsafe.Pointer(&privkey.key)) addr64 := (*[privateKeyLen]byte)(unsafe.Pointer(&privkey.key))
A := new(edwards25519.ExtendedGroupElement) A := new(edwards25519.ExtendedGroupElement)
edwards25519.GeScalarMultBase(A, addr32) edwards25519.GeScalarMultBase(A, addr32)
...@@ -120,6 +128,7 @@ func (privkey *RingSignPrivateKey) PubKey() crypto.PubKey { ...@@ -120,6 +128,7 @@ func (privkey *RingSignPrivateKey) PubKey() crypto.PubKey {
return publicKey return publicKey
} }
// Equals check key equal
func (privkey *RingSignPrivateKey) Equals(other crypto.PrivKey) bool { func (privkey *RingSignPrivateKey) Equals(other crypto.PrivKey) bool {
if otherPrivKey, ok := other.(*RingSignPrivateKey); ok { if otherPrivKey, ok := other.(*RingSignPrivateKey); ok {
return bytes.Equal(privkey.key[:], otherPrivKey.key[:]) return bytes.Equal(privkey.key[:], otherPrivKey.key[:])
...@@ -129,13 +138,15 @@ func (privkey *RingSignPrivateKey) Equals(other crypto.PrivKey) bool { ...@@ -129,13 +138,15 @@ func (privkey *RingSignPrivateKey) Equals(other crypto.PrivKey) bool {
// RingSignPublicKey 环签名中对于crypto.PubKey接口实现 // RingSignPublicKey 环签名中对于crypto.PubKey接口实现
type RingSignPublicKey struct { type RingSignPublicKey struct {
key [PublicKeyLen]byte key [publicKeyLen]byte
} }
// Bytes convert key to bytes
func (pubkey *RingSignPublicKey) Bytes() []byte { func (pubkey *RingSignPublicKey) Bytes() []byte {
return pubkey.key[:] return pubkey.key[:]
} }
// VerifyBytes verify bytes
func (pubkey *RingSignPublicKey) VerifyBytes(msg []byte, sign crypto.Signature) bool { func (pubkey *RingSignPublicKey) VerifyBytes(msg []byte, sign crypto.Signature) bool {
if len(msg) <= 0 { if len(msg) <= 0 {
return false return false
...@@ -170,10 +181,12 @@ func (pubkey *RingSignPublicKey) VerifyBytes(msg []byte, sign crypto.Signature) ...@@ -170,10 +181,12 @@ func (pubkey *RingSignPublicKey) VerifyBytes(msg []byte, sign crypto.Signature)
return true return true
} }
// KeyString convert key to string
func (pubkey *RingSignPublicKey) KeyString() string { func (pubkey *RingSignPublicKey) KeyString() string {
return fmt.Sprintf("%X", pubkey.key[:]) return fmt.Sprintf("%X", pubkey.key[:])
} }
// Equals check key is equal
func (pubkey *RingSignPublicKey) Equals(other crypto.PubKey) bool { func (pubkey *RingSignPublicKey) Equals(other crypto.PubKey) bool {
if otherPubKey, ok := other.(*RingSignPublicKey); ok { if otherPubKey, ok := other.(*RingSignPublicKey); ok {
return bytes.Equal(pubkey.key[:], otherPubKey.key[:]) return bytes.Equal(pubkey.key[:], otherPubKey.key[:])
...@@ -185,13 +198,14 @@ func (pubkey *RingSignPublicKey) Equals(other crypto.PubKey) bool { ...@@ -185,13 +198,14 @@ func (pubkey *RingSignPublicKey) Equals(other crypto.PubKey) bool {
type RingSignED25519 struct { type RingSignED25519 struct {
} }
// GenKey create privacy key
func (r *RingSignED25519) GenKey() (crypto.PrivKey, error) { func (r *RingSignED25519) GenKey() (crypto.PrivKey, error) {
privKeyPrivacyPtr := &PrivKeyPrivacy{} privKeyPrivacyPtr := &PrivKeyPrivacy{}
pubKeyPrivacyPtr := &PubKeyPrivacy{} pubKeyPrivacyPtr := &PubKeyPrivacy{}
copy(privKeyPrivacyPtr[:PrivateKeyLen], crypto.CRandBytes(PrivateKeyLen)) copy(privKeyPrivacyPtr[:privateKeyLen], crypto.CRandBytes(privateKeyLen))
addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyPrivacyPtr)) addr32 := (*[KeyLen32]byte)(unsafe.Pointer(privKeyPrivacyPtr))
addr64 := (*[PrivateKeyLen]byte)(unsafe.Pointer(privKeyPrivacyPtr)) addr64 := (*[privateKeyLen]byte)(unsafe.Pointer(privKeyPrivacyPtr))
edwards25519.ScReduce(addr32, addr64) edwards25519.ScReduce(addr32, addr64)
//to generate the publickey //to generate the publickey
...@@ -204,6 +218,7 @@ func (r *RingSignED25519) GenKey() (crypto.PrivKey, error) { ...@@ -204,6 +218,7 @@ func (r *RingSignED25519) GenKey() (crypto.PrivKey, error) {
return *privKeyPrivacyPtr, nil return *privKeyPrivacyPtr, nil
} }
// PrivKeyFromBytes create private key from bytes
func (r *RingSignED25519) PrivKeyFromBytes(b []byte) (crypto.PrivKey, error) { func (r *RingSignED25519) PrivKeyFromBytes(b []byte) (crypto.PrivKey, error) {
if len(b) <= 0 { if len(b) <= 0 {
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
...@@ -216,11 +231,12 @@ func (r *RingSignED25519) PrivKeyFromBytes(b []byte) (crypto.PrivKey, error) { ...@@ -216,11 +231,12 @@ func (r *RingSignED25519) PrivKeyFromBytes(b []byte) (crypto.PrivKey, error) {
return privateKey, nil return privateKey, nil
} }
// PubKeyFromBytes create publick key from bytes
func (r *RingSignED25519) PubKeyFromBytes(b []byte) (crypto.PubKey, error) { func (r *RingSignED25519) PubKeyFromBytes(b []byte) (crypto.PubKey, error) {
if len(b) <= 0 { if len(b) <= 0 {
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
} }
if len(b) != PublicKeyLen { if len(b) != publicKeyLen {
return nil, types.ErrPubKeyLen return nil, types.ErrPubKeyLen
} }
publicKey := new(RingSignPublicKey) publicKey := new(RingSignPublicKey)
...@@ -228,6 +244,7 @@ func (r *RingSignED25519) PubKeyFromBytes(b []byte) (crypto.PubKey, error) { ...@@ -228,6 +244,7 @@ func (r *RingSignED25519) PubKeyFromBytes(b []byte) (crypto.PubKey, error) {
return publicKey, nil return publicKey, nil
} }
// SignatureFromBytes create signature from bytes
func (r *RingSignED25519) SignatureFromBytes(b []byte) (crypto.Signature, error) { func (r *RingSignED25519) SignatureFromBytes(b []byte) (crypto.Signature, error) {
if len(b) <= 0 { if len(b) <= 0 {
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
......
...@@ -18,8 +18,8 @@ import ( ...@@ -18,8 +18,8 @@ import (
) )
var ( var (
pubs_byte [10][]byte pubsByte [10][]byte
secs_byte [10][]byte secsByte [10][]byte
) )
func init() { func init() {
...@@ -48,8 +48,8 @@ func init() { ...@@ -48,8 +48,8 @@ func init() {
} }
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
pubs_byte[i], _ = common.FromHex(pubstrs[i]) pubsByte[i], _ = common.FromHex(pubstrs[i])
secs_byte[i], _ = common.FromHex(secstrs[i]) secsByte[i], _ = common.FromHex(secstrs[i])
} }
} }
...@@ -104,7 +104,7 @@ func TestGenerateRingSignature1(t *testing.T) { ...@@ -104,7 +104,7 @@ func TestGenerateRingSignature1(t *testing.T) {
var sec PrivKeyPrivacy var sec PrivKeyPrivacy
var signs [maxCount]*Sign var signs [maxCount]*Sign
index := 0 index := 0
prefix_hash, err := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c") prefixHash, err := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c")
tmp, err := common.FromHex("e7d85d6e81512c5650adce0499d6c17a83e2e29a05c1166cd2171b6b9288b3c4") tmp, err := common.FromHex("e7d85d6e81512c5650adce0499d6c17a83e2e29a05c1166cd2171b6b9288b3c4")
copy(image[:], tmp) copy(image[:], tmp)
tmp, err = common.FromHex("15e3cc7cdb904d62f7c20d7fa51923fa2839f9e0a92ff0eddf8c12bd09089c15") tmp, err = common.FromHex("15e3cc7cdb904d62f7c20d7fa51923fa2839f9e0a92ff0eddf8c12bd09089c15")
...@@ -119,7 +119,7 @@ func TestGenerateRingSignature1(t *testing.T) { ...@@ -119,7 +119,7 @@ func TestGenerateRingSignature1(t *testing.T) {
for i := 0; i < maxCount; i++ { for i := 0; i < maxCount; i++ {
signs[i] = &Sign{} signs[i] = &Sign{}
} }
err = generateRingSignature(prefix_hash, &image, pubs[:], &sec, signs[:], index) err = generateRingSignature(prefixHash, &image, pubs[:], &sec, signs[:], index)
if err != nil { if err != nil {
t.Error("generateRingSignature() cause error ", err) t.Error("generateRingSignature() cause error ", err)
} }
...@@ -131,7 +131,7 @@ func TestCheckRingSignature1(t *testing.T) { ...@@ -131,7 +131,7 @@ func TestCheckRingSignature1(t *testing.T) {
var pubs [maxCount]*PubKeyPrivacy var pubs [maxCount]*PubKeyPrivacy
var signs [maxCount]*Sign var signs [maxCount]*Sign
prefix_hash, err := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c") prefixHash, err := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c")
if err != nil { if err != nil {
t.Error("initialize public key from hex failed.") t.Error("initialize public key from hex failed.")
} }
...@@ -150,7 +150,7 @@ func TestCheckRingSignature1(t *testing.T) { ...@@ -150,7 +150,7 @@ func TestCheckRingSignature1(t *testing.T) {
signs[i] = &sign signs[i] = &sign
} }
if !checkRingSignature(prefix_hash, &image, pubs[:], signs[:]) { if !checkRingSignature(prefixHash, &image, pubs[:], signs[:]) {
t.Fatal("checkRingSignature() failed.") t.Fatal("checkRingSignature() failed.")
} }
} }
...@@ -159,7 +159,7 @@ func TestCheckRingSignatureAPI1(t *testing.T) { ...@@ -159,7 +159,7 @@ func TestCheckRingSignatureAPI1(t *testing.T) {
const maxCount = 1 const maxCount = 1
var signatures types.RingSignatureItem var signatures types.RingSignatureItem
publickeys := make([][]byte, maxCount) publickeys := make([][]byte, maxCount)
prefix_hash, err := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c") prefixHash, err := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c")
if err != nil { if err != nil {
t.Errorf("common.FromHex.", err) t.Errorf("common.FromHex.", err)
} }
...@@ -181,7 +181,7 @@ func TestCheckRingSignatureAPI1(t *testing.T) { ...@@ -181,7 +181,7 @@ func TestCheckRingSignatureAPI1(t *testing.T) {
} }
signatures.Signature = data signatures.Signature = data
if !CheckRingSignature(prefix_hash, &signatures, publickeys, keyimage) { if !CheckRingSignature(prefixHash, &signatures, publickeys, keyimage) {
t.Fatal("checkRingSignature() failed.") t.Fatal("checkRingSignature() failed.")
} }
} }
...@@ -192,7 +192,7 @@ func TestCheckRingSignature3(t *testing.T) { ...@@ -192,7 +192,7 @@ func TestCheckRingSignature3(t *testing.T) {
var pubs [maxCount]*PubKeyPrivacy var pubs [maxCount]*PubKeyPrivacy
var signs [maxCount]*Sign var signs [maxCount]*Sign
prefix_hash, err := common.FromHex("9e7ff8bde0e318543dcedbe34c51c6b25a850578adae2e7930bbda5224c77ef5") prefixHash, err := common.FromHex("9e7ff8bde0e318543dcedbe34c51c6b25a850578adae2e7930bbda5224c77ef5")
if err != nil { if err != nil {
t.Error("initialize public key from hex failed.") t.Error("initialize public key from hex failed.")
} }
...@@ -211,7 +211,7 @@ func TestCheckRingSignature3(t *testing.T) { ...@@ -211,7 +211,7 @@ func TestCheckRingSignature3(t *testing.T) {
signs[i] = &sign signs[i] = &sign
} }
if !checkRingSignature(prefix_hash, &image, pubs[:], signs[:]) { if !checkRingSignature(prefixHash, &image, pubs[:], signs[:]) {
t.Fatal("checkRingSignature() failed.") t.Fatal("checkRingSignature() failed.")
} }
} }
...@@ -242,7 +242,7 @@ func TestCheckRingSignature17(t *testing.T) { ...@@ -242,7 +242,7 @@ func TestCheckRingSignature17(t *testing.T) {
"c618c6b0e328886be15e2c92052dcf74cf4745a4e5e53f6d2417a9c9d139c167", "c618c6b0e328886be15e2c92052dcf74cf4745a4e5e53f6d2417a9c9d139c167",
} }
prefix_hash, err := common.FromHex("1c909782c70567e9968ded1c05a4226a3e04a07ae9db48e0153a56b2a4684779") prefixHash, err := common.FromHex("1c909782c70567e9968ded1c05a4226a3e04a07ae9db48e0153a56b2a4684779")
if err != nil { if err != nil {
t.Error("initialize public key from hex failed.") t.Error("initialize public key from hex failed.")
} }
...@@ -262,7 +262,7 @@ func TestCheckRingSignature17(t *testing.T) { ...@@ -262,7 +262,7 @@ func TestCheckRingSignature17(t *testing.T) {
signs[i] = &sign signs[i] = &sign
} }
if !checkRingSignature(prefix_hash, &image, pubs[:], signs[:]) { if !checkRingSignature(prefixHash, &image, pubs[:], signs[:]) {
t.Fatal("checkRingSignature() failed.") t.Fatal("checkRingSignature() failed.")
} }
} }
...@@ -276,27 +276,27 @@ func TestRingSignatere1(t *testing.T) { ...@@ -276,27 +276,27 @@ func TestRingSignatere1(t *testing.T) {
index := 0 index := 0
// 初始化测试数据 // 初始化测试数据
prefix_hash, _ := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c") prefixHash, _ := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c")
for i := 0; i < maxCount; i++ { for i := 0; i < maxCount; i++ {
pub := PubKeyPrivacy{} pub := PubKeyPrivacy{}
sign := Sign{} sign := Sign{}
pubs[i] = &pub pubs[i] = &pub
signs[i] = &sign signs[i] = &sign
copy(pub[:], pubs_byte[i]) copy(pub[:], pubsByte[i])
if i == index { if i == index {
// 创建 KeyImage // 创建 KeyImage
copy(sec[:], secs_byte[i]) copy(sec[:], secsByte[i])
generateKeyImage(&pub, &sec, &image) generateKeyImage(&pub, &sec, &image)
} }
} }
// 创建环签名 // 创建环签名
err := generateRingSignature(prefix_hash, &image, pubs[:], &sec, signs[:], index) err := generateRingSignature(prefixHash, &image, pubs[:], &sec, signs[:], index)
if err != nil { if err != nil {
t.Fatal("generateRingSignature() failed. error ", err) t.Fatal("generateRingSignature() failed. error ", err)
} }
// 消炎环签名 // 消炎环签名
if !checkRingSignature(prefix_hash, &image, pubs[:], signs[:]) { if !checkRingSignature(prefixHash, &image, pubs[:], signs[:]) {
t.Fatal("checkRingSignature() failed.") t.Fatal("checkRingSignature() failed.")
} }
} }
...@@ -309,7 +309,7 @@ func testRingSignatureOncetime(maxCount int, t *testing.T) { ...@@ -309,7 +309,7 @@ func testRingSignatureOncetime(maxCount int, t *testing.T) {
signs := make([]*Sign, maxCount) signs := make([]*Sign, maxCount)
// 初始化测试数据 // 初始化测试数据
prefix_hash, _ := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c") prefixHash, _ := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c")
c, err := crypto.New(types.GetSignName("privacy", privacytypes.OnetimeED25519)) c, err := crypto.New(types.GetSignName("privacy", privacytypes.OnetimeED25519))
if err != nil { if err != nil {
...@@ -339,12 +339,12 @@ func testRingSignatureOncetime(maxCount int, t *testing.T) { ...@@ -339,12 +339,12 @@ func testRingSignatureOncetime(maxCount int, t *testing.T) {
} }
} }
// 创建环签名 // 创建环签名
err = generateRingSignature(prefix_hash, &image, pubs[:], &sec, signs[:], index) err = generateRingSignature(prefixHash, &image, pubs[:], &sec, signs[:], index)
if err != nil { if err != nil {
t.Fatal("generateRingSignature() failed. error ", err) t.Fatal("generateRingSignature() failed. error ", err)
} }
// 消炎环签名 // 消炎环签名
if !checkRingSignature(prefix_hash, &image, pubs[:], signs[:]) { if !checkRingSignature(prefixHash, &image, pubs[:], signs[:]) {
t.Fatal("checkRingSignature() failed.") t.Fatal("checkRingSignature() failed.")
} }
} }
...@@ -371,12 +371,12 @@ func TestGenerateRingSignatureAPI(t *testing.T) { ...@@ -371,12 +371,12 @@ func TestGenerateRingSignatureAPI(t *testing.T) {
} }
realUtxoIndex := rand.Int() % maxCount realUtxoIndex := rand.Int() % maxCount
prefix_hash, _ := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c") prefixHash, _ := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c")
utxos = make([]*privacytypes.UTXOBasic, maxCount) utxos = make([]*privacytypes.UTXOBasic, maxCount)
for i := 0; i < maxCount; i++ { for i := 0; i < maxCount; i++ {
utxo := privacytypes.UTXOBasic{} utxo := privacytypes.UTXOBasic{}
utxos[i] = &utxo utxos[i] = &utxo
utxo.OnetimePubkey = append(utxo.OnetimePubkey[:], pubs_byte[i]...) utxo.OnetimePubkey = append(utxo.OnetimePubkey[:], pubsByte[i]...)
if i == realUtxoIndex { if i == realUtxoIndex {
pubKey := privkey.PubKey().Bytes() pubKey := privkey.PubKey().Bytes()
// 增加指定的密钥对 // 增加指定的密钥对
...@@ -394,7 +394,7 @@ func TestGenerateRingSignatureAPI(t *testing.T) { ...@@ -394,7 +394,7 @@ func TestGenerateRingSignatureAPI(t *testing.T) {
var signaturedata *types.RingSignatureItem var signaturedata *types.RingSignatureItem
// step2. generate ring signature // step2. generate ring signature
if signaturedata, err = GenerateRingSignature(prefix_hash, utxos, sec[:], realUtxoIndex, keyImage); err != nil { if signaturedata, err = GenerateRingSignature(prefixHash, utxos, sec[:], realUtxoIndex, keyImage); err != nil {
t.Errorf("GenerateRingSignature() failed. ", err) t.Errorf("GenerateRingSignature() failed. ", err)
} }
...@@ -403,7 +403,7 @@ func TestGenerateRingSignatureAPI(t *testing.T) { ...@@ -403,7 +403,7 @@ func TestGenerateRingSignatureAPI(t *testing.T) {
publickeys[i] = append(publickeys[i], utxos[i].OnetimePubkey...) publickeys[i] = append(publickeys[i], utxos[i].OnetimePubkey...)
} }
// step3. checksignature // step3. checksignature
if !CheckRingSignature(prefix_hash, signaturedata, publickeys, keyImage) { if !CheckRingSignature(prefixHash, signaturedata, publickeys, keyImage) {
t.Error("CheckRingSignature() failed.") t.Error("CheckRingSignature() failed.")
} }
} }
...@@ -416,7 +416,7 @@ func benchRingSignatureOncetime(maxCount int) { ...@@ -416,7 +416,7 @@ func benchRingSignatureOncetime(maxCount int) {
signs := make([]*Sign, maxCount) signs := make([]*Sign, maxCount)
// 初始化测试数据 // 初始化测试数据
prefix_hash, _ := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c") prefixHash, _ := common.FromHex("fd1f64844a7d6a9f74fc2141bceba9d9d69b1fd6104f93bfa42a6d708a6ab22c")
c, _ := crypto.New(types.GetSignName("privacy", privacytypes.OnetimeED25519)) c, _ := crypto.New(types.GetSignName("privacy", privacytypes.OnetimeED25519))
for i := 0; i < maxCount; i++ { for i := 0; i < maxCount; i++ {
...@@ -437,9 +437,9 @@ func benchRingSignatureOncetime(maxCount int) { ...@@ -437,9 +437,9 @@ func benchRingSignatureOncetime(maxCount int) {
} }
} }
// 创建环签名 // 创建环签名
generateRingSignature(prefix_hash, &image, pubs[:], &sec, signs[:], index) generateRingSignature(prefixHash, &image, pubs[:], &sec, signs[:], index)
// 效验环签名 // 效验环签名
checkRingSignature(prefix_hash, &image, pubs[:], signs[:]) checkRingSignature(prefixHash, &image, pubs[:], signs[:])
} }
func Benchmark_RingSignature(b *testing.B) { func Benchmark_RingSignature(b *testing.B) {
......
...@@ -8,34 +8,38 @@ import ( ...@@ -8,34 +8,38 @@ import (
"bytes" "bytes"
"fmt" "fmt"
. "github.com/33cn/chain33/common/crypto" "github.com/33cn/chain33/common/crypto"
) )
// Signature // SignatureOnetime sinature data type
type SignatureOnetime [64]byte type SignatureOnetime [64]byte
// SignatureS signature data
type SignatureS struct { type SignatureS struct {
Signature crypto.Signature
} }
// Bytes get bytes
func (sig SignatureOnetime) Bytes() []byte { func (sig SignatureOnetime) Bytes() []byte {
s := make([]byte, 64) s := make([]byte, 64)
copy(s, sig[:]) copy(s, sig[:])
return s return s
} }
// IsZero check is zero
func (sig SignatureOnetime) IsZero() bool { return len(sig) == 0 } func (sig SignatureOnetime) IsZero() bool { return len(sig) == 0 }
// String format to string
func (sig SignatureOnetime) String() string { func (sig SignatureOnetime) String() string {
fingerprint := make([]byte, len(sig[:])) fingerprint := make([]byte, len(sig[:]))
copy(fingerprint, sig[:]) copy(fingerprint, sig[:])
return fmt.Sprintf("/%X.../", fingerprint) return fmt.Sprintf("/%X.../", fingerprint)
} }
func (sig SignatureOnetime) Equals(other Signature) bool { // Equals check signature equal
func (sig SignatureOnetime) Equals(other crypto.Signature) bool {
if otherEd, ok := other.(SignatureOnetime); ok { if otherEd, ok := other.(SignatureOnetime); ok {
return bytes.Equal(sig[:], otherEd[:]) return bytes.Equal(sig[:], otherEd[:])
} else {
return false
} }
return false
} }
...@@ -11,6 +11,7 @@ import ( ...@@ -11,6 +11,7 @@ import (
ty "github.com/33cn/plugin/plugin/dapp/privacy/types" ty "github.com/33cn/plugin/plugin/dapp/privacy/types"
) )
// Exec_Public2Privacy execute public to privacy
func (p *privacy) Exec_Public2Privacy(payload *ty.Public2Privacy, tx *types.Transaction, index int) (*types.Receipt, error) { func (p *privacy) Exec_Public2Privacy(payload *ty.Public2Privacy, tx *types.Transaction, index int) (*types.Receipt, error) {
if payload.Tokenname != types.BTY { if payload.Tokenname != types.BTY {
return nil, types.ErrNotSupport return nil, types.ErrNotSupport
...@@ -50,6 +51,7 @@ func (p *privacy) Exec_Public2Privacy(payload *ty.Public2Privacy, tx *types.Tran ...@@ -50,6 +51,7 @@ func (p *privacy) Exec_Public2Privacy(payload *ty.Public2Privacy, tx *types.Tran
return receipt, nil return receipt, nil
} }
// Exec_Privacy2Privacy execute privacy to privacy transaction
func (p *privacy) Exec_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Transaction, index int) (*types.Receipt, error) { func (p *privacy) Exec_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Transaction, index int) (*types.Receipt, error) {
if payload.Tokenname != types.BTY { if payload.Tokenname != types.BTY {
return nil, types.ErrNotSupport return nil, types.ErrNotSupport
...@@ -58,7 +60,7 @@ func (p *privacy) Exec_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Tr ...@@ -58,7 +60,7 @@ func (p *privacy) Exec_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Tr
receipt := &types.Receipt{KV: make([]*types.KeyValue, 0)} receipt := &types.Receipt{KV: make([]*types.KeyValue, 0)}
privacyInput := payload.Input privacyInput := payload.Input
for _, keyInput := range privacyInput.Keyinput { for _, keyInput := range privacyInput.Keyinput {
value := []byte{KeyImageSpentAlready} value := []byte{keyImageSpentAlready}
key := calcPrivacyKeyImageKey(payload.Tokenname, keyInput.KeyImage) key := calcPrivacyKeyImageKey(payload.Tokenname, keyInput.KeyImage)
stateDB := p.GetStateDB() stateDB := p.GetStateDB()
stateDB.Set(key, value) stateDB.Set(key, value)
...@@ -91,6 +93,7 @@ func (p *privacy) Exec_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Tr ...@@ -91,6 +93,7 @@ func (p *privacy) Exec_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Tr
return receipt, nil return receipt, nil
} }
// Exec_Privacy2Public execute privacy to public transaction
func (p *privacy) Exec_Privacy2Public(payload *ty.Privacy2Public, tx *types.Transaction, index int) (*types.Receipt, error) { func (p *privacy) Exec_Privacy2Public(payload *ty.Privacy2Public, tx *types.Transaction, index int) (*types.Receipt, error) {
if payload.Tokenname != types.BTY { if payload.Tokenname != types.BTY {
return nil, types.ErrNotSupport return nil, types.ErrNotSupport
...@@ -104,7 +107,7 @@ func (p *privacy) Exec_Privacy2Public(payload *ty.Privacy2Public, tx *types.Tran ...@@ -104,7 +107,7 @@ func (p *privacy) Exec_Privacy2Public(payload *ty.Privacy2Public, tx *types.Tran
} }
privacyInput := payload.Input privacyInput := payload.Input
for _, keyInput := range privacyInput.Keyinput { for _, keyInput := range privacyInput.Keyinput {
value := []byte{KeyImageSpentAlready} value := []byte{keyImageSpentAlready}
key := calcPrivacyKeyImageKey(payload.Tokenname, keyInput.KeyImage) key := calcPrivacyKeyImageKey(payload.Tokenname, keyInput.KeyImage)
stateDB := p.GetStateDB() stateDB := p.GetStateDB()
stateDB.Set(key, value) stateDB.Set(key, value)
......
...@@ -87,14 +87,17 @@ func (p *privacy) execDelLocal(tx *types.Transaction, receiptData *types.Receipt ...@@ -87,14 +87,17 @@ func (p *privacy) execDelLocal(tx *types.Transaction, receiptData *types.Receipt
return dbSet, nil return dbSet, nil
} }
// ExecDelLocal_Public2Privacy local delete execute public to privacy transaction
func (p *privacy) ExecDelLocal_Public2Privacy(payload *ty.Public2Privacy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (p *privacy) ExecDelLocal_Public2Privacy(payload *ty.Public2Privacy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return p.execDelLocal(tx, receiptData, index) return p.execDelLocal(tx, receiptData, index)
} }
// ExecDelLocal_Privacy2Privacy local delete execute privacy to privacy transaction
func (p *privacy) ExecDelLocal_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (p *privacy) ExecDelLocal_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return p.execDelLocal(tx, receiptData, index) return p.execDelLocal(tx, receiptData, index)
} }
// ExecDelLocal_Privacy2Public local delete execute public to public transaction
func (p *privacy) ExecDelLocal_Privacy2Public(payload *ty.Privacy2Public, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (p *privacy) ExecDelLocal_Privacy2Public(payload *ty.Privacy2Public, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return p.execDelLocal(tx, receiptData, index) return p.execDelLocal(tx, receiptData, index)
} }
...@@ -101,14 +101,17 @@ func (p *privacy) execLocal(receiptData *types.ReceiptData, tx *types.Transactio ...@@ -101,14 +101,17 @@ func (p *privacy) execLocal(receiptData *types.ReceiptData, tx *types.Transactio
return dbSet, nil return dbSet, nil
} }
func (g *privacy) ExecLocal_Public2Privacy(payload *ty.Public2Privacy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { // ExecLocal_Public2Privacy local execute public to privacy transaction
return g.execLocal(receiptData, tx, index) func (p *privacy) ExecLocal_Public2Privacy(payload *ty.Public2Privacy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return p.execLocal(receiptData, tx, index)
} }
func (g *privacy) ExecLocal_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { // ExecLocal_Privacy2Privacy local execute privacy to privacy transaction
return g.execLocal(receiptData, tx, index) func (p *privacy) ExecLocal_Privacy2Privacy(payload *ty.Privacy2Privacy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return p.execLocal(receiptData, tx, index)
} }
func (g *privacy) ExecLocal_Privacy2Public(payload *ty.Privacy2Public, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { // ExecLocal_Privacy2Public local execute privacy to public trasaction
return g.execLocal(receiptData, tx, index) func (p *privacy) ExecLocal_Privacy2Public(payload *ty.Privacy2Public, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return p.execLocal(receiptData, tx, index)
} }
...@@ -11,39 +11,41 @@ import ( ...@@ -11,39 +11,41 @@ import (
) )
const ( const (
PrivacyOutputKeyPrefix = "mavl-privacy-UTXO-tahi" privacyOutputKeyPrefix = "mavl-privacy-UTXO-tahi"
PrivacyKeyImagePrefix = "mavl-privacy-UTXO-keyimage" privacyKeyImagePrefix = "mavl-privacy-UTXO-keyimage"
PrivacyUTXOKEYPrefix = "LODB-privacy-UTXO-tahhi" privacyUTXOKEYPrefix = "LODB-privacy-UTXO-tahhi"
PrivacyAmountTypePrefix = "LODB-privacy-UTXO-atype" privacyAmountTypePrefix = "LODB-privacy-UTXO-atype"
PrivacyTokenTypesPrefix = "LODB-privacy-UTXO-token" privacyTokenTypesPrefix = "LODB-privacy-UTXO-token"
KeyImageSpentAlready = 0x01 keyImageSpentAlready = 0x01
Invalid_index = -1 invalidIndex = -1
) )
//该key对应的是types.KeyOutput //CalcPrivacyOutputKey 该key对应的是types.KeyOutput
//该kv会在store中设置 //该kv会在store中设置
func CalcPrivacyOutputKey(token string, amount int64, txhash string, outindex int) (key []byte) { func CalcPrivacyOutputKey(token string, amount int64, txhash string, outindex int) (key []byte) {
return []byte(fmt.Sprintf(PrivacyOutputKeyPrefix+"-%s-%d-%s-%d", token, amount, txhash, outindex)) return []byte(fmt.Sprintf(privacyOutputKeyPrefix+"-%s-%d-%s-%d", token, amount, txhash, outindex))
} }
func calcPrivacyKeyImageKey(token string, keyimage []byte) []byte { func calcPrivacyKeyImageKey(token string, keyimage []byte) []byte {
return []byte(fmt.Sprintf(PrivacyKeyImagePrefix+"-%s-%s", token, common.ToHex(keyimage))) return []byte(fmt.Sprintf(privacyKeyImagePrefix+"-%s-%s", token, common.ToHex(keyimage)))
} }
//在本地数据库中设置一条可以找到对应amount的对应的utxo的global index //CalcPrivacyUTXOkeyHeight 在本地数据库中设置一条可以找到对应amount的对应的utxo的global index
func CalcPrivacyUTXOkeyHeight(token string, amount, height int64, txhash string, txindex, outindex int) (key []byte) { func CalcPrivacyUTXOkeyHeight(token string, amount, height int64, txhash string, txindex, outindex int) (key []byte) {
return []byte(fmt.Sprintf(PrivacyUTXOKEYPrefix+"-%s-%d-%d-%s-%d-%d", token, amount, height, txhash, txindex, outindex)) return []byte(fmt.Sprintf(privacyUTXOKEYPrefix+"-%s-%d-%d-%s-%d-%d", token, amount, height, txhash, txindex, outindex))
} }
// CalcPrivacyUTXOkeyHeightPrefix get privacy utxo key by height and prefix
func CalcPrivacyUTXOkeyHeightPrefix(token string, amount int64) (key []byte) { func CalcPrivacyUTXOkeyHeightPrefix(token string, amount int64) (key []byte) {
return []byte(fmt.Sprintf(PrivacyUTXOKEYPrefix+"-%s-%d-", token, amount)) return []byte(fmt.Sprintf(privacyUTXOKEYPrefix+"-%s-%d-", token, amount))
} }
//设置当前系统存在的token的amount的类型,如存在1,3,5,100...等等的类型, //CalcprivacyKeyTokenAmountType 设置当前系统存在的token的amount的类型,如存在1,3,5,100...等等的类型,
func CalcprivacyKeyTokenAmountType(token string) (key []byte) { func CalcprivacyKeyTokenAmountType(token string) (key []byte) {
return []byte(fmt.Sprintf(PrivacyAmountTypePrefix+"-%s-", token)) return []byte(fmt.Sprintf(privacyAmountTypePrefix+"-%s-", token))
} }
// CalcprivacyKeyTokenTypes get privacy token types key
func CalcprivacyKeyTokenTypes() (key []byte) { func CalcprivacyKeyTokenTypes() (key []byte) {
return []byte(PrivacyTokenTypesPrefix) return []byte(privacyTokenTypesPrefix)
} }
...@@ -41,12 +41,14 @@ func init() { ...@@ -41,12 +41,14 @@ func init() {
ety.InitFuncList(types.ListMethod(&privacy{})) ety.InitFuncList(types.ListMethod(&privacy{}))
} }
// Init initialize executor driver
func Init(name string, sub []byte) { func Init(name string, sub []byte) {
drivers.Register(GetName(), newPrivacy, types.GetDappFork(driverName, "Enable")) drivers.Register(GetName(), newPrivacy, types.GetDappFork(driverName, "Enable"))
// 如果需要在开发环境下使用隐私交易,则需要使用下面这行代码,否则用上面的代码 // 如果需要在开发环境下使用隐私交易,则需要使用下面这行代码,否则用上面的代码
//drivers.Register(newPrivacy().GetName(), newPrivacy, 0) //drivers.Register(newPrivacy().GetName(), newPrivacy, 0)
} }
// GetName get privacy name
func GetName() string { func GetName() string {
return newPrivacy().GetName() return newPrivacy().GetName()
} }
...@@ -62,6 +64,7 @@ func newPrivacy() drivers.Driver { ...@@ -62,6 +64,7 @@ func newPrivacy() drivers.Driver {
return t return t
} }
// GetDriverName get driver name
func (p *privacy) GetDriverName() string { func (p *privacy) GetDriverName() string {
return driverName return driverName
} }
...@@ -142,7 +145,7 @@ func (p *privacy) getGlobalUtxoIndex(getUtxoIndexReq *pty.ReqUTXOGlobalIndex) (t ...@@ -142,7 +145,7 @@ func (p *privacy) getGlobalUtxoIndex(getUtxoIndexReq *pty.ReqUTXOGlobalIndex) (t
return utxoGlobalIndexResp, nil return utxoGlobalIndexResp, nil
} }
//获取指定amount下的所有utxo,这样就可以查询当前系统不同amout下存在的UTXO,可以帮助查询用于混淆用的资源 //ShowAmountsOfUTXO 获取指定amount下的所有utxo,这样就可以查询当前系统不同amout下存在的UTXO,可以帮助查询用于混淆用的资源
//也可以确认币种的碎片化问题 //也可以确认币种的碎片化问题
//显示存在的各种不同的额度的UTXO,如1,3,5,10,20,30,100... //显示存在的各种不同的额度的UTXO,如1,3,5,10,20,30,100...
func (p *privacy) ShowAmountsOfUTXO(reqtoken *pty.ReqPrivacyToken) (types.Message, error) { func (p *privacy) ShowAmountsOfUTXO(reqtoken *pty.ReqPrivacyToken) (types.Message, error) {
...@@ -171,7 +174,7 @@ func (p *privacy) ShowAmountsOfUTXO(reqtoken *pty.ReqPrivacyToken) (types.Messag ...@@ -171,7 +174,7 @@ func (p *privacy) ShowAmountsOfUTXO(reqtoken *pty.ReqPrivacyToken) (types.Messag
return replyAmounts, nil return replyAmounts, nil
} }
//显示在指定额度下的UTXO的具体信息,如区块高度,交易hash,输出索引等具体信息 //ShowUTXOs4SpecifiedAmount 显示在指定额度下的UTXO的具体信息,如区块高度,交易hash,输出索引等具体信息
func (p *privacy) ShowUTXOs4SpecifiedAmount(reqtoken *pty.ReqPrivacyToken) (types.Message, error) { func (p *privacy) ShowUTXOs4SpecifiedAmount(reqtoken *pty.ReqPrivacyToken) (types.Message, error) {
querydb := p.GetLocalDB() querydb := p.GetLocalDB()
...@@ -193,6 +196,7 @@ func (p *privacy) ShowUTXOs4SpecifiedAmount(reqtoken *pty.ReqPrivacyToken) (type ...@@ -193,6 +196,7 @@ func (p *privacy) ShowUTXOs4SpecifiedAmount(reqtoken *pty.ReqPrivacyToken) (type
return &replyUTXOsOfAmount, nil return &replyUTXOsOfAmount, nil
} }
// CheckTx check transaction
func (p *privacy) CheckTx(tx *types.Transaction, index int) error { func (p *privacy) CheckTx(tx *types.Transaction, index int) error {
txhashstr := common.Bytes2Hex(tx.Hash()) txhashstr := common.Bytes2Hex(tx.Hash())
var action pty.PrivacyAction var action pty.PrivacyAction
...@@ -288,11 +292,11 @@ func (p *privacy) checkUTXOValid(keyImages [][]byte) (bool, int32) { ...@@ -288,11 +292,11 @@ func (p *privacy) checkUTXOValid(keyImages [][]byte) (bool, int32) {
values, err := stateDB.BatchGet(keyImages) values, err := stateDB.BatchGet(keyImages)
if err != nil { if err != nil {
privacylog.Error("exec module", "checkUTXOValid failed to get value from statDB") privacylog.Error("exec module", "checkUTXOValid failed to get value from statDB")
return false, Invalid_index return false, invalidIndex
} }
if len(values) != len(keyImages) { if len(values) != len(keyImages) {
privacylog.Error("exec module", "checkUTXOValid return different count value with keys") privacylog.Error("exec module", "checkUTXOValid return different count value with keys")
return false, Invalid_index return false, invalidIndex
} }
for i, value := range values { for i, value := range values {
if value != nil { if value != nil {
...@@ -301,19 +305,19 @@ func (p *privacy) checkUTXOValid(keyImages [][]byte) (bool, int32) { ...@@ -301,19 +305,19 @@ func (p *privacy) checkUTXOValid(keyImages [][]byte) (bool, int32) {
} }
} }
return true, Invalid_index return true, invalidIndex
} }
func (p *privacy) checkPubKeyValid(keys [][]byte, pubkeys [][]byte) (bool, int32) { func (p *privacy) checkPubKeyValid(keys [][]byte, pubkeys [][]byte) (bool, int32) {
values, err := p.GetStateDB().BatchGet(keys) values, err := p.GetStateDB().BatchGet(keys)
if err != nil { if err != nil {
privacylog.Error("exec module", "checkPubKeyValid failed to get value from statDB with err", err) privacylog.Error("exec module", "checkPubKeyValid failed to get value from statDB with err", err)
return false, Invalid_index return false, invalidIndex
} }
if len(values) != len(pubkeys) { if len(values) != len(pubkeys) {
privacylog.Error("exec module", "checkPubKeyValid return different count value with keys") privacylog.Error("exec module", "checkPubKeyValid return different count value with keys")
return false, Invalid_index return false, invalidIndex
} }
for i, value := range values { for i, value := range values {
...@@ -325,5 +329,5 @@ func (p *privacy) checkPubKeyValid(keys [][]byte, pubkeys [][]byte) (bool, int32 ...@@ -325,5 +329,5 @@ func (p *privacy) checkPubKeyValid(keys [][]byte, pubkeys [][]byte) (bool, int32
} }
} }
return true, Invalid_index return true, invalidIndex
} }
// Copyright Fuzamei Corp. 2018 All Rights Reserved. // Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style // Use of p source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package executor package executor
...@@ -9,18 +9,22 @@ import ( ...@@ -9,18 +9,22 @@ import (
pty "github.com/33cn/plugin/plugin/dapp/privacy/types" pty "github.com/33cn/plugin/plugin/dapp/privacy/types"
) )
func (this *privacy) Query_ShowAmountsOfUTXO(param *pty.ReqPrivacyToken) (types.Message, error) { // Query_ShowAmountsOfUTXO show amount of utxo
return this.ShowAmountsOfUTXO(param) func (p *privacy) Query_ShowAmountsOfUTXO(param *pty.ReqPrivacyToken) (types.Message, error) {
return p.ShowAmountsOfUTXO(param)
} }
func (this *privacy) Query_ShowUTXOs4SpecifiedAmount(param *pty.ReqPrivacyToken) (types.Message, error) { // Query_ShowUTXOs4SpecifiedAmount shwo utxos for specified amount
return this.ShowUTXOs4SpecifiedAmount(param) func (p *privacy) Query_ShowUTXOs4SpecifiedAmount(param *pty.ReqPrivacyToken) (types.Message, error) {
return p.ShowUTXOs4SpecifiedAmount(param)
} }
func (this *privacy) Query_GetUTXOGlobalIndex(param *pty.ReqUTXOGlobalIndex) (types.Message, error) { // Query_GetUTXOGlobalIndex get utxo global index
return this.getGlobalUtxoIndex(param) func (p *privacy) Query_GetUTXOGlobalIndex(param *pty.ReqUTXOGlobalIndex) (types.Message, error) {
return p.getGlobalUtxoIndex(param)
} }
func (this *privacy) Query_GetTxsByAddr(param *types.ReqAddr) (types.Message, error) { // Query_GetTxsByAddr get transactions by address
return this.GetTxsByAddr(param) func (p *privacy) Query_GetTxsByAddr(param *types.ReqAddr) (types.Message, error) {
return p.GetTxsByAddr(param)
} }
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