github.com/turingchain2020/turingchain@v1.1.21/executor/authority/test/sm2/authority_sm2_test.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sm2_test
     6  
     7  import (
     8  	"fmt"
     9  	"testing"
    10  
    11  	"github.com/turingchain2020/turingchain/executor/authority"
    12  	"github.com/turingchain2020/turingchain/executor/authority/utils"
    13  
    14  	"github.com/turingchain2020/turingchain/common"
    15  	"github.com/turingchain2020/turingchain/common/address"
    16  	"github.com/turingchain2020/turingchain/common/crypto"
    17  	secp256r1_util "github.com/turingchain2020/turingchain/system/crypto/secp256r1"
    18  	sm2_util "github.com/turingchain2020/turingchain/system/crypto/sm2"
    19  	cty "github.com/turingchain2020/turingchain/system/dapp/coins/types"
    20  	"github.com/turingchain2020/turingchain/types"
    21  	"github.com/stretchr/testify/assert"
    22  
    23  	_ "github.com/turingchain2020/turingchain/system"
    24  )
    25  
    26  var (
    27  	transfer = &cty.CoinsAction{Value: nil, Ty: cty.CoinsActionTransfer}
    28  	to       = address.PubKeyToAddress(privKey.PubKey().Bytes()).String()
    29  	tx1      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 1000000, Expire: 2, To: to}
    30  	tx2      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100000000, Expire: 0, To: to}
    31  	tx3      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 200000000, Expire: 0, To: to}
    32  	tx4      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 300000000, Expire: 0, To: to}
    33  	tx5      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 400000000, Expire: 0, To: to}
    34  	tx6      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 500000000, Expire: 0, To: to}
    35  	tx7      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 600000000, Expire: 0, To: to}
    36  	tx8      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 700000000, Expire: 0, To: to}
    37  	tx9      = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 800000000, Expire: 0, To: to}
    38  	tx10     = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 900000000, Expire: 0, To: to}
    39  	tx11     = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 450000000, Expire: 0, To: to}
    40  	tx12     = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 460000000, Expire: 0, To: to}
    41  	tx13     = &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: 100, Expire: 0, To: to}
    42  	txs      = []*types.Transaction{tx1, tx2, tx3, tx4, tx5, tx6, tx7, tx8, tx9, tx10, tx11, tx12}
    43  
    44  	privRaw, _  = common.FromHex("CC38546E9E659D15E6B4893F0AB32A06D103931A8230B0BDE71459D2B27D6944")
    45  	tr          = &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: int64(1e8)}}
    46  	secpp256, _ = crypto.New(types.GetSignName("", types.SECP256K1))
    47  	privKey, _  = secpp256.PrivKeyFromBytes(privRaw)
    48  	tx14        = &types.Transaction{
    49  		Execer:  []byte("coins"),
    50  		Payload: types.Encode(&cty.CoinsAction{Value: tr, Ty: cty.CoinsActionTransfer}),
    51  		Fee:     1000000,
    52  		Expire:  2,
    53  		To:      address.PubKeyToAddress(privKey.PubKey().Bytes()).String(),
    54  	}
    55  )
    56  
    57  var USERNAME = "user1"
    58  var ORGNAME = "org1"
    59  var SIGNTYPE = sm2_util.ID
    60  
    61  func signtx(tx *types.Transaction, priv crypto.PrivKey, cert []byte) {
    62  	tx.Sign(int32(SIGNTYPE), priv)
    63  	tx.Signature.Signature = utils.EncodeCertToSignature(tx.Signature.Signature, cert, nil)
    64  }
    65  
    66  func signtxs(priv crypto.PrivKey, cert []byte) {
    67  	signtx(tx1, priv, cert)
    68  	signtx(tx2, priv, cert)
    69  	signtx(tx3, priv, cert)
    70  	signtx(tx4, priv, cert)
    71  	signtx(tx5, priv, cert)
    72  	signtx(tx6, priv, cert)
    73  	signtx(tx7, priv, cert)
    74  	signtx(tx8, priv, cert)
    75  	signtx(tx9, priv, cert)
    76  	signtx(tx10, priv, cert)
    77  	signtx(tx11, priv, cert)
    78  	signtx(tx12, priv, cert)
    79  	signtx(tx13, priv, cert)
    80  }
    81  
    82  /**
    83  初始化Author实例和userloader
    84  */
    85  func initEnv() (*types.TuringchainConfig, error) {
    86  	cfg := types.NewTuringchainConfig(types.ReadFile("./turingchain.auth.test.toml"))
    87  	sub := cfg.GetSubConfig()
    88  	var subcfg types.AuthorityCfg
    89  	if sub.Exec["cert"] != nil {
    90  		types.MustDecode(sub.Exec["cert"], &subcfg)
    91  	}
    92  	authority.Author.Init(&subcfg)
    93  	SIGNTYPE = types.GetSignType("cert", subcfg.SignType)
    94  
    95  	userLoader := &authority.UserLoader{}
    96  	err := userLoader.Init(subcfg.CryptoPath, subcfg.SignType)
    97  	if err != nil {
    98  		fmt.Printf("Init user loader falied -> %v", err)
    99  		return nil, err
   100  	}
   101  
   102  	user, err := userLoader.Get(USERNAME, ORGNAME)
   103  	if err != nil {
   104  		fmt.Printf("Get user failed")
   105  		return nil, err
   106  	}
   107  
   108  	signtxs(user.Key, user.Cert)
   109  	if err != nil {
   110  		fmt.Printf("Init authority failed")
   111  		return nil, err
   112  	}
   113  
   114  	return cfg, nil
   115  }
   116  
   117  /**
   118  TestCase01 带证书的交易验签
   119  */
   120  func TestChckSign(t *testing.T) {
   121  	cfg, err := initEnv()
   122  	if err != nil {
   123  		t.Errorf("init env failed, error:%s", err)
   124  		return
   125  	}
   126  	cfg.SetMinFee(0)
   127  
   128  	assert.Equal(t, true, tx1.CheckSign())
   129  }
   130  
   131  /**
   132  TestCase10 带证书的多交易验签
   133  */
   134  func TestChckSigns(t *testing.T) {
   135  	cfg, err := initEnv()
   136  	if err != nil {
   137  		t.Errorf("init env failed, error:%s", err)
   138  		return
   139  	}
   140  	cfg.SetMinFee(0)
   141  
   142  	for i, tx := range txs {
   143  		if !tx.CheckSign() {
   144  			t.Error(fmt.Sprintf("error check tx[%d]", i+1))
   145  			return
   146  		}
   147  	}
   148  }
   149  
   150  /**
   151  TestCase02 带证书的交易并行验签
   152  */
   153  func TestChckSignsPara(t *testing.T) {
   154  	cfg, err := initEnv()
   155  	if err != nil {
   156  		t.Errorf("init env failed, error:%s", err)
   157  		return
   158  	}
   159  	cfg.SetMinFee(0)
   160  
   161  	block := types.Block{}
   162  	block.Txs = txs
   163  	if !block.CheckSign(cfg) {
   164  		t.Error("error check txs")
   165  		return
   166  	}
   167  }
   168  
   169  /**
   170  TestCase03 不带证书,公链签名算法验证
   171  */
   172  func TestChckSignWithNoneAuth(t *testing.T) {
   173  	cfg, err := initEnv()
   174  	if err != nil {
   175  		t.Errorf("init env failed, error:%s", err)
   176  		return
   177  	}
   178  	cfg.SetMinFee(0)
   179  
   180  	tx14.Sign(types.SECP256K1, privKey)
   181  	if !tx14.CheckSign() {
   182  		t.Error("check signature failed")
   183  		return
   184  	}
   185  }
   186  
   187  /**
   188  TestCase04 不带证书,SM2签名验证
   189  */
   190  func TestChckSignWithSm2(t *testing.T) {
   191  	sm2, err := crypto.New(types.GetSignName("cert", sm2_util.ID))
   192  	assert.Nil(t, err)
   193  	privKeysm2, _ := sm2.PrivKeyFromBytes(privRaw)
   194  	tx15 := &types.Transaction{Execer: []byte("coins"),
   195  		Payload: types.Encode(&cty.CoinsAction{Value: tr, Ty: cty.CoinsActionTransfer}),
   196  		Fee:     1000000, Expire: 2, To: address.PubKeyToAddress(privKeysm2.PubKey().Bytes()).String()}
   197  
   198  	cfg, err := initEnv()
   199  	if err != nil {
   200  		t.Errorf("init env failed, error:%s", err)
   201  		return
   202  	}
   203  	cfg.SetMinFee(0)
   204  
   205  	tx15.Sign(sm2_util.ID, privKeysm2)
   206  	if !tx15.CheckSign() {
   207  		t.Error("check signature failed")
   208  		return
   209  	}
   210  }
   211  
   212  /**
   213  TestCase05 不带证书,secp256r1签名验证
   214  */
   215  func TestChckSignWithEcdsa(t *testing.T) {
   216  	ecdsacrypto, _ := crypto.New(types.GetSignName("cert", secp256r1_util.ID))
   217  	privKeyecdsa, _ := ecdsacrypto.PrivKeyFromBytes(privRaw)
   218  	tx16 := &types.Transaction{Execer: []byte("coins"),
   219  		Payload: types.Encode(&cty.CoinsAction{Value: tr, Ty: cty.CoinsActionTransfer}),
   220  		Fee:     1000000, Expire: 2, To: address.PubKeyToAddress(privKeyecdsa.PubKey().Bytes()).String()}
   221  
   222  	cfg, err := initEnv()
   223  	if err != nil {
   224  		t.Errorf("init env failed, error:%s", err)
   225  		return
   226  	}
   227  	cfg.SetMinFee(0)
   228  
   229  	tx16.Sign(secp256r1_util.ID, privKeyecdsa)
   230  	if !tx16.CheckSign() {
   231  		t.Error("check signature failed")
   232  		return
   233  	}
   234  }
   235  
   236  /**
   237  TestCase 06 证书检验
   238  */
   239  func TestValidateCert(t *testing.T) {
   240  	cfg, err := initEnv()
   241  	if err != nil {
   242  		t.Errorf("init env failed, error:%s", err)
   243  		return
   244  	}
   245  
   246  	cfg.SetMinFee(0)
   247  
   248  	for _, tx := range txs {
   249  		err = authority.Author.Validate(tx.Signature)
   250  		if err != nil {
   251  			t.Error("error cert validate", err.Error())
   252  			return
   253  		}
   254  	}
   255  }
   256  
   257  /**
   258  Testcase07 noneimpl校验器验证(回滚到未开启证书验证的区块使用)
   259  */
   260  func TestValidateTxWithNoneAuth(t *testing.T) {
   261  	cfg, err := initEnv()
   262  	if err != nil {
   263  		t.Errorf("init env failed, error:%s", err)
   264  		return
   265  	}
   266  	noneCertdata := &types.HistoryCertStore{}
   267  	noneCertdata.CurHeigth = 0
   268  	authority.Author.ReloadCert(noneCertdata)
   269  
   270  	cfg.SetMinFee(0)
   271  
   272  	err = authority.Author.Validate(tx14.Signature)
   273  	if err != nil {
   274  		t.Error("error cert validate", err.Error())
   275  		return
   276  	}
   277  }
   278  
   279  /**
   280  Testcase08 重载历史证书
   281  */
   282  func TestReloadCert(t *testing.T) {
   283  	cfg, err := initEnv()
   284  	if err != nil {
   285  		t.Errorf("init env failed, error:%s", err)
   286  		return
   287  	}
   288  
   289  	cfg.SetMinFee(0)
   290  
   291  	store := &types.HistoryCertStore{}
   292  
   293  	authority.Author.ReloadCert(store)
   294  
   295  	err = authority.Author.Validate(tx1.Signature)
   296  	if err != nil {
   297  		t.Error(err.Error())
   298  	}
   299  }
   300  
   301  /**
   302  Testcase09 根据高度重载历史证书
   303  */
   304  func TestReloadByHeight(t *testing.T) {
   305  	cfg, err := initEnv()
   306  	if err != nil {
   307  		t.Errorf("init env failed, error:%s", err)
   308  		return
   309  	}
   310  	cfg.SetMinFee(0)
   311  
   312  	authority.Author.ReloadCertByHeght(30)
   313  	if authority.Author.HistoryCertCache.CurHeight != 30 {
   314  		t.Error("reload by height failed")
   315  	}
   316  }