Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
TATAUFO committed May 21, 2020
1 parent abc9f19 commit 2ee6fa9
Show file tree
Hide file tree
Showing 18 changed files with 533 additions and 112 deletions.
4 changes: 2 additions & 2 deletions cmd/pdu/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,14 @@ func generate() error {
if err != nil {
return err
}
keyJson, err := engine.EncryptKey(privateKey, string(passwd))
keyJSON, err := engine.EncryptKey(privateKey, string(passwd))
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(accOutput), 0700); err != nil {
return fmt.Errorf("could not create directory %s", filepath.Dir(accOutput))
}
if err := ioutil.WriteFile(accOutput, keyJson, 0600); err != nil {
if err := ioutil.WriteFile(accOutput, keyJSON, 0600); err != nil {
return fmt.Errorf("failed to write keyfile to %s: %v", accOutput, err)
}
fmt.Println(accOutput, "is created success.")
Expand Down
8 changes: 4 additions & 4 deletions cmd/pdu/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func unlockKeyByCmd() (*crypto.PrivateKey, *crypto.PublicKey, error) {
var keyFile string
fmt.Print("KeyFile path: ")
fmt.Scan(&keyFile)
keyJson, err := ioutil.ReadFile(keyFile)
keyJSON, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, nil, err
}
Expand All @@ -121,11 +121,11 @@ func unlockKeyByCmd() (*crypto.PrivateKey, *crypto.PublicKey, error) {
return nil, nil, err
}

return utils.DecryptKey(keyJson, string(passwd))
return utils.DecryptKey(keyJSON, string(passwd))
}

func unlockKeyByFile(keyFile, passFile string) (*crypto.PrivateKey, *crypto.PublicKey, error) {
keyJson, err := ioutil.ReadFile(keyFile)
keyJSON, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, nil, err
}
Expand All @@ -135,7 +135,7 @@ func unlockKeyByFile(keyFile, passFile string) (*crypto.PrivateKey, *crypto.Publ
return nil, nil, err
}

return utils.DecryptKey(keyJson, strings.TrimSpace(string(passwd)))
return utils.DecryptKey(keyJSON, strings.TrimSpace(string(passwd)))
}

func scanLine(input *string) {
Expand Down
5 changes: 3 additions & 2 deletions core/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (a *Auth) UnmarshalJSON(input []byte) error {
if err != nil {
return err
}
pk, err := engine.UnmarshalJSON(input)
_, pk, err := engine.Unmarshal(nil, input)
if err != nil {
return err
}
Expand All @@ -55,5 +55,6 @@ func (a Auth) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
return engine.MarshalJSON(a.PublicKey)
_, pkBytes, err := engine.Marshal(nil, &a.PublicKey)
return pkBytes, err
}
11 changes: 6 additions & 5 deletions core/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ package core
import (
"crypto/ecdsa"
"encoding/json"
"github.com/pdupub/go-pdu/crypto"
"github.com/pdupub/go-pdu/crypto/ethereum"
"testing"

"github.com/pdupub/go-pdu/crypto"
"github.com/pdupub/go-pdu/crypto/utils"
)

func TestAuth_MarshalJSON(t *testing.T) {
engine := ethereum.New()
engine, _ := utils.SelectEngine(defaultEngineName)
_, pubKey, err := engine.GenKey(crypto.Signature2PublicKey)
if err != nil {
t.Errorf("pdu genereate key fail, err: %s", err)
Expand All @@ -49,8 +50,8 @@ func TestAuth_MarshalJSON(t *testing.T) {
t.Errorf("pubkey info mismatch")
}

pubKey1 := pubKey.PubKey.(ecdsa.PublicKey)
pubKey2 := targetAuth.PubKey.(ecdsa.PublicKey)
pubKey1 := pubKey.PubKey.(*ecdsa.PublicKey)
pubKey2 := targetAuth.PubKey.(*ecdsa.PublicKey)
if pubKey1.X.Cmp(pubKey2.X) != 0 || pubKey1.Y.Cmp(pubKey2.Y) != 0 {
t.Errorf("public key mismatch")
}
Expand Down
24 changes: 24 additions & 0 deletions core/content_evidence.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package core

import "crypto"

const (
// LeakedPrivateKey is the evidence can prove a private key has been leaked.
// Usually contain 1 anonymous msg(TypeText), the content is private key
Expand All @@ -39,3 +41,25 @@ type ContentEvidence struct {
func CreateContentEvidence(evidenceType int, msgs []*Message) *ContentEvidence {
return &ContentEvidence{EvidenceType: evidenceType, Msgs: msgs}
}

// CreateLPCE create the evidence of leaked privatekey
func CreateLPCE(privKey crypto.PrivateKey, msg *Message) (*ContentEvidence, error) {
// check relation of privKey & msg.SenderID.Auth

// create anonymous msg which content is privKey
msgPrivateKey := &Message{}
// create content evidence by two messages

return &ContentEvidence{EvidenceType: LeakedPrivateKey, Msgs: []*Message{msgPrivateKey, msg}}, nil
}

// CreateEBCE creaste the evidence of ExcessiveBirth
func CreateEBCE(msgs ...*Message) (*ContentEvidence, error) {
// check all msgs from same SenderID

// check if two msgs in spacetime

// two msgs illeagal at least on one spacetime local universe

return &ContentEvidence{EvidenceType: ExcessiveBirth, Msgs: msgs}, nil
}
29 changes: 29 additions & 0 deletions core/content_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2019 The PDU Authors
// This file is part of the PDU library.
//
// The PDU library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The PDU library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the PDU library. If not, see <http://www.gnu.org/licenses/>.

package core

import (
"testing"
)

func TestContentBirth(t *testing.T) {

}

func TestContentEvidence(t *testing.T) {

}
2 changes: 2 additions & 0 deletions core/msg_value.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ const (
TypeText = iota
// TypeBirth is the type which contain the cosign to create new user in pdu
TypeBirth
// TypeEvidence is the type which contain the illegal evidence of user
TypeEvidence
)

// MsgValue is the mas value
Expand Down
8 changes: 7 additions & 1 deletion core/universe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,14 @@ var (
universeEngine crypto.Engine
)

const (
//defaultEngineName = crypto.PDU
//defaultEngineName = crypto.ETH
defaultEngineName = crypto.BTC
)

func TestNewUniverse(t *testing.T) {
universeEngine, _ = utils.SelectEngine(crypto.ETH)
universeEngine, _ = utils.SelectEngine(defaultEngineName)

// Test 1: Create root users, Adam and Eve , create universe
// The gender of user relate to public key (random), so createRootUser
Expand Down
9 changes: 5 additions & 4 deletions core/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
"testing"

"github.com/pdupub/go-pdu/crypto"
"github.com/pdupub/go-pdu/crypto/ethereum"
"github.com/pdupub/go-pdu/crypto/utils"
)

const (
Expand All @@ -34,7 +34,7 @@ var (
)

func TestCreateRootUsersS2PK(t *testing.T) {
userEngine = ethereum.New()
userEngine, _ = utils.SelectEngine(defaultEngineName)
var f, m bool
for i := 0; i < retryCnt; i++ {
if _, pubKey, err := userEngine.GenKey(crypto.Signature2PublicKey); err != nil {
Expand All @@ -58,16 +58,17 @@ func TestCreateRootUsersS2PK(t *testing.T) {
}
}
}

func TestCreateRootUsersMS(t *testing.T) {
var f, m bool
for i := 0; i < retryCnt; i++ {
if _, pubKey, err := userEngine.GenKey(crypto.MultipleSignatures, 3); err != nil {

t.Error("generate key fail", err)
} else {
user := CreateRootUser(*pubKey, "name", "extra")

if user.ID() != copy(user).ID() {
t.Errorf("%s : %s json Encode & Decode fail ", userEngine.Name(), crypto.Signature2PublicKey)
t.Errorf("%s : %s json Encode & Decode fail ", userEngine.Name(), crypto.MultipleSignatures)
}
if user.Gender() {
m = true
Expand Down
80 changes: 59 additions & 21 deletions crypto/bitcoin/btc_crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ import (
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"math/big"

btc "github.com/btcsuite/btcd/btcec"
"github.com/pdupub/go-pdu/crypto"
"math/big"

"github.com/ethereum/go-ethereum/accounts/keystore"
eth "github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -56,7 +57,7 @@ func (e BEngine) GenKey(params ...interface{}) (*crypto.PrivateKey, *crypto.Publ
if err != nil {
return nil, nil, err
}
return &crypto.PrivateKey{Source: e.name, SigType: crypto.Signature2PublicKey, PriKey: pk}, &crypto.PublicKey{Source: e.name, SigType: crypto.Signature2PublicKey, PubKey: pk.PublicKey}, nil
return &crypto.PrivateKey{Source: e.name, SigType: crypto.Signature2PublicKey, PriKey: pk}, &crypto.PublicKey{Source: e.name, SigType: crypto.Signature2PublicKey, PubKey: &pk.PublicKey}, nil

case crypto.MultipleSignatures:
if len(params) == 1 {
Expand All @@ -69,7 +70,7 @@ func (e BEngine) GenKey(params ...interface{}) (*crypto.PrivateKey, *crypto.Publ
return nil, nil, err
}
privKeys = append(privKeys, pk)
pubKeys = append(pubKeys, pk.PublicKey)
pubKeys = append(pubKeys, &pk.PublicKey)
}
return &crypto.PrivateKey{Source: e.name, SigType: crypto.MultipleSignatures, PriKey: privKeys}, &crypto.PublicKey{Source: e.name, SigType: crypto.MultipleSignatures, PubKey: pubKeys}, nil
default:
Expand Down Expand Up @@ -203,7 +204,7 @@ func (e BEngine) Verify(hash []byte, sig *crypto.Signature) (bool, error) {
currentSig = append(currentSig, v)
} else {
currentSig = append(currentSig, v)
currentSigLeft -= 1
currentSigLeft--
if currentSigLeft == 0 {
sigs = append(sigs, currentSig)
currentSigLeft = -1
Expand All @@ -225,8 +226,27 @@ func (e BEngine) Verify(hash []byte, sig *crypto.Signature) (bool, error) {
}
}

// UnmarshalJSON unmarshal public key from json
func (e BEngine) UnmarshalJSON(input []byte) (*crypto.PublicKey, error) {
// Unmarshal unmarshal private & public key
func (e BEngine) Unmarshal(privKeyBytes, pubKeyBytes []byte) (privKey *crypto.PrivateKey, pubKey *crypto.PublicKey, err error) {

if len(pubKeyBytes) > 0 {
if pubKey, err = e.unmarshalPubKey(pubKeyBytes); err != nil {
return
}
}
if len(privKeyBytes) > 0 {
if privKey, err = e.unmarshalPrivKey(privKeyBytes); err != nil {
return
}
}
return
}

func (e BEngine) unmarshalPrivKey(input []byte) (*crypto.PrivateKey, error) {
return nil, nil
}

func (e BEngine) unmarshalPubKey(input []byte) (*crypto.PublicKey, error) {
p := crypto.PublicKey{}
aMap := make(map[string]interface{})
err := json.Unmarshal(input, &aMap)
Expand All @@ -246,10 +266,10 @@ func (e BEngine) UnmarshalJSON(input []byte) (*crypto.PublicKey, error) {
if err != nil {
return nil, err
}
p.PubKey = *pubKey.ToECDSA()
p.PubKey = pubKey.ToECDSA()
} else if p.SigType == crypto.MultipleSignatures {
pks := aMap["pubKey"].([]interface{})
var pubKeys []ecdsa.PublicKey
var pubKeys []*ecdsa.PublicKey
for _, v := range pks {
pk, err := hex.DecodeString(v.(string))
if err != nil {
Expand All @@ -259,7 +279,7 @@ func (e BEngine) UnmarshalJSON(input []byte) (*crypto.PublicKey, error) {
if err != nil {
return nil, err
}
pubKeys = append(pubKeys, *pubKey.ToECDSA())
pubKeys = append(pubKeys, pubKey.ToECDSA())
}
p.PubKey = pubKeys
} else {
Expand All @@ -272,32 +292,50 @@ func (e BEngine) UnmarshalJSON(input []byte) (*crypto.PublicKey, error) {
return &p, nil
}

// MarshalJSON marshal public key to json
func (e BEngine) MarshalJSON(a crypto.PublicKey) ([]byte, error) {
// Marshal marshal private & public key
func (e BEngine) Marshal(privKey *crypto.PrivateKey, pubKey *crypto.PublicKey) (privKeyBytes []byte, pubKeyBytes []byte, err error) {
if privKey != nil {
if privKeyBytes, err = e.marshalPrivKey(privKey); err != nil {
return
}
}
if pubKey != nil {
if pubKeyBytes, err = e.marshalPubKey(pubKey); err != nil {
return
}
}
return
}

func (e BEngine) marshalPrivKey(a *crypto.PrivateKey) ([]byte, error) {
return []byte{}, nil
}

func (e BEngine) marshalPubKey(a *crypto.PublicKey) ([]byte, error) {
aMap := make(map[string]interface{})
aMap["source"] = a.Source
aMap["sigType"] = a.SigType
if a.Source == e.name {
if a.SigType == crypto.Signature2PublicKey {
pk := a.PubKey.(ecdsa.PublicKey)
bpk := (btc.PublicKey)(pk)
pk := a.PubKey.(*ecdsa.PublicKey)
bpk := (btc.PublicKey)(*pk)
aMap["pubKey"] = hex.EncodeToString(bpk.SerializeUncompressed())
} else if a.SigType == crypto.MultipleSignatures {
switch a.PubKey.(type) {
case []ecdsa.PublicKey:
pks := a.PubKey.([]ecdsa.PublicKey)
case []*ecdsa.PublicKey:
pks := a.PubKey.([]*ecdsa.PublicKey)
pubKey := make([]string, len(pks))
for i, pk := range pks {
bpk := (btc.PublicKey)(pk)
bpk := (btc.PublicKey)(*pk)
pubKey[i] = hex.EncodeToString(bpk.SerializeUncompressed())
}
aMap["pubKey"] = pubKey
case []interface{}:
pks := a.PubKey.([]interface{})
pubKey := make([]string, len(pks))
for i, v := range pks {
pk := v.(ecdsa.PublicKey)
bpk := (btc.PublicKey)(pk)
pk := v.(*ecdsa.PublicKey)
bpk := (btc.PublicKey)(*pk)
pubKey[i] = hex.EncodeToString(bpk.SerializeUncompressed())
}
aMap["pubKey"] = pubKey
Expand Down Expand Up @@ -363,16 +401,16 @@ func (e BEngine) encryptKey(priKey *ecdsa.PrivateKey, pass string) (*crypto.Encr
encryptedKeyJSONV3 := crypto.EncryptedKeyJSONV3{
Address: hex.EncodeToString(key.Address[:]),
Crypto: cryptoStruct,
Id: key.Id.String(),
ID: key.Id.String(),
Version: crypto.EncryptedVersion,
}
return &encryptedKeyJSONV3, nil
}

// DecryptKey decrypt private key from file
func (e BEngine) DecryptKey(keyJson []byte, pass string) (*crypto.PrivateKey, *crypto.PublicKey, error) {
func (e BEngine) DecryptKey(keyJSON []byte, pass string) (*crypto.PrivateKey, *crypto.PublicKey, error) {
var k crypto.EncryptedPrivateKey
if err := json.Unmarshal(keyJson, &k); err != nil {
if err := json.Unmarshal(keyJSON, &k); err != nil {
return nil, nil, err
} else if k.Source != crypto.BTC {
return nil, nil, crypto.ErrSourceNotMatch
Expand Down
Loading

0 comments on commit 2ee6fa9

Please sign in to comment.