Best K6 code snippet using crypto.Update
systemchannel_test.go
Source:systemchannel_test.go
...26 NewChannelConfigErr error27}28func newMockConfigTXValidator(err error) *mocks.ConfigTXValidator {29 mockValidator := &mocks.ConfigTXValidator{}30 mockValidator.ProposeConfigUpdateReturns(&cb.ConfigEnvelope{}, err)31 return mockValidator32}33func (mscs *mockSystemChannelSupport) NewChannelConfig(env *cb.Envelope) (channelconfig.Resources, error) {34 mockResources := &mocks.Resources{}35 mockResources.ConfigtxValidatorReturns(mscs.NewChannelConfigVal)36 return mockResources, mscs.NewChannelConfigErr37}38func TestProcessSystemChannelNormalMsg(t *testing.T) {39 t.Run("Missing header", func(t *testing.T) {40 mscs := &mockSystemChannelSupport{}41 ms := &mockSystemChannelFilterSupport{42 OrdererConfigVal: &mocks.OrdererConfig{},43 }44 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())45 require.NoError(t, err)46 _, err = NewSystemChannel(ms, mscs, nil, cryptoProvider).ProcessNormalMsg(&cb.Envelope{})47 require.NotNil(t, err)48 require.Regexp(t, "header not set", err.Error())49 })50 t.Run("Mismatched channel ID", func(t *testing.T) {51 mscs := &mockSystemChannelSupport{}52 ms := &mockSystemChannelFilterSupport{53 OrdererConfigVal: &mocks.OrdererConfig{},54 }55 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())56 require.NoError(t, err)57 _, err = NewSystemChannel(ms, mscs, nil, cryptoProvider).ProcessNormalMsg(&cb.Envelope{58 Payload: protoutil.MarshalOrPanic(&cb.Payload{59 Header: &cb.Header{60 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{61 ChannelId: testChannelID + ".different",62 }),63 },64 }),65 })66 require.Equal(t, ErrChannelDoesNotExist, err)67 })68 t.Run("Good", func(t *testing.T) {69 mscs := &mockSystemChannelSupport{}70 ms := &mockSystemChannelFilterSupport{71 SequenceVal: 7,72 OrdererConfigVal: newMockOrdererConfig(true, orderer.ConsensusType_STATE_NORMAL),73 }74 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())75 require.NoError(t, err)76 cs, err := NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessNormalMsg(&cb.Envelope{77 Payload: protoutil.MarshalOrPanic(&cb.Payload{78 Header: &cb.Header{79 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{80 ChannelId: testChannelID,81 }),82 },83 }),84 })85 require.Nil(t, err)86 require.Equal(t, ms.SequenceVal, cs)87 })88}89func TestSystemChannelConfigUpdateMsg(t *testing.T) {90 t.Run("Missing header", func(t *testing.T) {91 mscs := &mockSystemChannelSupport{}92 ms := &mockSystemChannelFilterSupport{93 OrdererConfigVal: &mocks.OrdererConfig{},94 }95 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())96 require.NoError(t, err)97 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigUpdateMsg(&cb.Envelope{})98 require.NotNil(t, err)99 require.Regexp(t, "header not set", err.Error())100 })101 t.Run("NormalUpdate", func(t *testing.T) {102 mscs := &mockSystemChannelSupport{}103 ms := &mockSystemChannelFilterSupport{104 SequenceVal: 7,105 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},106 OrdererConfigVal: newMockOrdererConfig(true, orderer.ConsensusType_STATE_NORMAL),107 }108 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())109 require.NoError(t, err)110 sysChan := NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider)111 sysChan.maintenanceFilter = AcceptRule112 config, cs, err := sysChan.ProcessConfigUpdateMsg(&cb.Envelope{113 Payload: protoutil.MarshalOrPanic(&cb.Payload{114 Header: &cb.Header{115 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{116 ChannelId: testChannelID,117 }),118 },119 }),120 })121 require.NotNil(t, config)122 require.Equal(t, cs, ms.SequenceVal)123 require.Nil(t, err)124 })125 t.Run("BadNewChannelConfig", func(t *testing.T) {126 mscs := &mockSystemChannelSupport{127 NewChannelConfigErr: fmt.Errorf("An error"),128 }129 ms := &mockSystemChannelFilterSupport{130 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},131 OrdererConfigVal: &mocks.OrdererConfig{},132 }133 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())134 require.NoError(t, err)135 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigUpdateMsg(&cb.Envelope{136 Payload: protoutil.MarshalOrPanic(&cb.Payload{137 Header: &cb.Header{138 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{139 ChannelId: testChannelID + "different",140 }),141 },142 }),143 })144 require.Equal(t, mscs.NewChannelConfigErr, err)145 })146 t.Run("BadProposedUpdate", func(t *testing.T) {147 mscs := &mockSystemChannelSupport{148 NewChannelConfigVal: newMockConfigTXValidator(fmt.Errorf("An error")),149 }150 ms := &mockSystemChannelFilterSupport{151 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},152 OrdererConfigVal: &mocks.OrdererConfig{},153 }154 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())155 require.NoError(t, err)156 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigUpdateMsg(&cb.Envelope{157 Payload: protoutil.MarshalOrPanic(&cb.Payload{158 Header: &cb.Header{159 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{160 ChannelId: testChannelID + "different",161 }),162 },163 }),164 })165 require.EqualError(t, err, "error validating channel creation transaction for new channel 'foodifferent', could not successfully apply update to template configuration: An error")166 })167 t.Run("BadSignEnvelope", func(t *testing.T) {168 mscs := &mockSystemChannelSupport{169 NewChannelConfigVal: &mocks.ConfigTXValidator{},170 }171 ms := &mockSystemChannelFilterSupport{172 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},173 OrdererConfigVal: &mocks.OrdererConfig{},174 }175 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())176 require.NoError(t, err)177 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigUpdateMsg(&cb.Envelope{178 Payload: protoutil.MarshalOrPanic(&cb.Payload{179 Header: &cb.Header{180 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{181 ChannelId: testChannelID + "different",182 }),183 },184 }),185 })186 require.Regexp(t, "Marshal called with nil", err)187 })188 t.Run("BadByFilter", func(t *testing.T) {189 mscs := &mockSystemChannelSupport{190 NewChannelConfigVal: newMockConfigTXValidator(nil),191 }192 ms := &mockSystemChannelFilterSupport{193 SequenceVal: 7,194 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},195 OrdererConfigVal: &mocks.OrdererConfig{},196 }197 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())198 require.NoError(t, err)199 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{RejectRule}), cryptoProvider).ProcessConfigUpdateMsg(&cb.Envelope{200 Payload: protoutil.MarshalOrPanic(&cb.Payload{201 Header: &cb.Header{202 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{203 ChannelId: testChannelID + "different",204 }),205 },206 }),207 })208 require.Equal(t, RejectRule.Apply(nil), err)209 })210 t.Run("RejectByMaintenance", func(t *testing.T) {211 mscs := &mockSystemChannelSupport{212 NewChannelConfigVal: newMockConfigTXValidator(nil),213 }214 ms := &mockSystemChannelFilterSupport{215 SequenceVal: 7,216 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},217 OrdererConfigVal: &mocks.OrdererConfig{},218 }219 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())220 require.NoError(t, err)221 sysChan := NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider)222 sysChan.maintenanceFilter = RejectRule223 _, _, err = sysChan.ProcessConfigUpdateMsg(&cb.Envelope{224 Payload: protoutil.MarshalOrPanic(&cb.Payload{225 Header: &cb.Header{226 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{227 ChannelId: testChannelID,228 }),229 },230 }),231 })232 require.Equal(t, RejectRule.Apply(nil), errors.Cause(err))233 })234 t.Run("Good", func(t *testing.T) {235 mscs := &mockSystemChannelSupport{236 NewChannelConfigVal: newMockConfigTXValidator(nil),237 }238 ms := &mockSystemChannelFilterSupport{239 SequenceVal: 7,240 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},241 OrdererConfigVal: &mocks.OrdererConfig{},242 }243 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())244 require.NoError(t, err)245 config, cs, err := NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigUpdateMsg(&cb.Envelope{246 Payload: protoutil.MarshalOrPanic(&cb.Payload{247 Header: &cb.Header{248 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{249 ChannelId: testChannelID + "different",250 }),251 },252 }),253 })254 require.Equal(t, cs, ms.SequenceVal)255 require.NotNil(t, config)256 require.Nil(t, err)257 })258}259func TestSystemChannelConfigMsg(t *testing.T) {260 t.Run("ConfigMsg", func(t *testing.T) {261 t.Run("BadPayloadData", func(t *testing.T) {262 mscs := &mockSystemChannelSupport{263 NewChannelConfigVal: newMockConfigTXValidator(nil),264 }265 ms := &mockSystemChannelFilterSupport{266 SequenceVal: 7,267 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},268 OrdererConfigVal: &mocks.OrdererConfig{},269 }270 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())271 require.NoError(t, err)272 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigMsg(&cb.Envelope{273 Payload: protoutil.MarshalOrPanic(&cb.Payload{274 Header: &cb.Header{275 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{276 ChannelId: testChannelID,277 Type: int32(cb.HeaderType_CONFIG),278 }),279 },280 Data: []byte("hello"),281 }),282 })283 require.Error(t, err)284 })285 t.Run("Good", func(t *testing.T) {286 mscs := &mockSystemChannelSupport{287 NewChannelConfigVal: newMockConfigTXValidator(nil),288 }289 ms := &mockSystemChannelFilterSupport{290 SequenceVal: 7,291 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},292 OrdererConfigVal: newMockOrdererConfig(false, orderer.ConsensusType_STATE_NORMAL),293 }294 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())295 require.NoError(t, err)296 sysChan := NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider)297 sysChan.maintenanceFilter = AcceptRule298 config, seq, err := sysChan.ProcessConfigMsg(&cb.Envelope{299 Payload: protoutil.MarshalOrPanic(&cb.Payload{300 Header: &cb.Header{301 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{302 ChannelId: testChannelID,303 Type: int32(cb.HeaderType_CONFIG),304 }),305 },306 }),307 })308 require.Equal(t, seq, ms.SequenceVal)309 require.NotNil(t, config)310 require.Nil(t, err)311 hdr, err := protoutil.ChannelHeader(config)312 require.NoError(t, err)313 require.Equal(314 t,315 int32(cb.HeaderType_CONFIG),316 hdr.Type,317 "Expect type of returned envelope to be %d, but got %d", cb.HeaderType_CONFIG, hdr.Type)318 })319 })320 t.Run("OrdererTxMsg", func(t *testing.T) {321 t.Run("BadPayloadData", func(t *testing.T) {322 mscs := &mockSystemChannelSupport{323 NewChannelConfigVal: newMockConfigTXValidator(nil),324 }325 ms := &mockSystemChannelFilterSupport{326 SequenceVal: 7,327 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},328 OrdererConfigVal: &mocks.OrdererConfig{},329 }330 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())331 require.NoError(t, err)332 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigMsg(&cb.Envelope{333 Payload: protoutil.MarshalOrPanic(&cb.Payload{334 Header: &cb.Header{335 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{336 ChannelId: testChannelID,337 Type: int32(cb.HeaderType_ORDERER_TRANSACTION),338 }),339 },340 Data: []byte("hello"),341 }),342 })343 require.Error(t, err)344 })345 t.Run("WrongEnvelopeType", func(t *testing.T) {346 mscs := &mockSystemChannelSupport{347 NewChannelConfigVal: newMockConfigTXValidator(nil),348 }349 ms := &mockSystemChannelFilterSupport{350 SequenceVal: 7,351 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},352 OrdererConfigVal: &mocks.OrdererConfig{},353 }354 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())355 require.NoError(t, err)356 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigMsg(&cb.Envelope{357 Payload: protoutil.MarshalOrPanic(&cb.Payload{358 Header: &cb.Header{359 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{360 ChannelId: testChannelID,361 Type: int32(cb.HeaderType_ORDERER_TRANSACTION),362 }),363 },364 Data: protoutil.MarshalOrPanic(&cb.Envelope{365 Payload: protoutil.MarshalOrPanic(&cb.Payload{366 Header: &cb.Header{367 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{368 ChannelId: testChannelID,369 Type: int32(cb.HeaderType_MESSAGE),370 }),371 },372 }),373 }),374 }),375 })376 require.Error(t, err)377 })378 t.Run("GoodConfigMsg", func(t *testing.T) {379 mscs := &mockSystemChannelSupport{380 NewChannelConfigVal: newMockConfigTXValidator(nil),381 }382 ms := &mockSystemChannelFilterSupport{383 SequenceVal: 7,384 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},385 OrdererConfigVal: &mocks.OrdererConfig{},386 }387 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())388 require.NoError(t, err)389 config, seq, err := NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigMsg(&cb.Envelope{390 Payload: protoutil.MarshalOrPanic(&cb.Payload{391 Header: &cb.Header{392 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{393 ChannelId: testChannelID,394 Type: int32(cb.HeaderType_ORDERER_TRANSACTION),395 }),396 },397 Data: protoutil.MarshalOrPanic(&cb.Envelope{398 Payload: protoutil.MarshalOrPanic(&cb.Payload{399 Header: &cb.Header{400 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{401 ChannelId: testChannelID,402 Type: int32(cb.HeaderType_CONFIG),403 }),404 },405 Data: protoutil.MarshalOrPanic(&cb.ConfigEnvelope{406 LastUpdate: &cb.Envelope{407 Payload: protoutil.MarshalOrPanic(&cb.Payload{408 Header: &cb.Header{409 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{410 ChannelId: testChannelID + "different",411 Type: int32(cb.HeaderType_CONFIG_UPDATE),412 }),413 },414 }),415 },416 }),417 }),418 }),419 }),420 })421 require.Equal(t, seq, ms.SequenceVal)422 require.NotNil(t, config)423 require.Nil(t, err)424 hdr, err := protoutil.ChannelHeader(config)425 require.NoError(t, err)426 require.Equal(427 t,428 int32(cb.HeaderType_ORDERER_TRANSACTION),429 hdr.Type,430 "Expect type of returned envelope to be %d, but got %d", cb.HeaderType_ORDERER_TRANSACTION, hdr.Type)431 })432 })433 t.Run("OtherMsgType", func(t *testing.T) {434 mscs := &mockSystemChannelSupport{435 NewChannelConfigVal: newMockConfigTXValidator(nil),436 }437 ms := &mockSystemChannelFilterSupport{438 SequenceVal: 7,439 ProposeConfigUpdateVal: &cb.ConfigEnvelope{},440 OrdererConfigVal: &mocks.OrdererConfig{},441 }442 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())443 require.NoError(t, err)444 _, _, err = NewSystemChannel(ms, mscs, NewRuleSet([]Rule{AcceptRule}), cryptoProvider).ProcessConfigMsg(&cb.Envelope{445 Payload: protoutil.MarshalOrPanic(&cb.Payload{446 Header: &cb.Header{447 ChannelHeader: protoutil.MarshalOrPanic(&cb.ChannelHeader{448 ChannelId: testChannelID,449 Type: int32(cb.HeaderType_MESSAGE),450 }),451 },452 }),453 })454 require.Error(t, err)455 })456}457type mockDefaultTemplatorSupport struct {458 channelconfig.Resources459}460func (mdts *mockDefaultTemplatorSupport) Signer() identity.SignerSerializer {461 return nil462}463func TestNewChannelConfig(t *testing.T) {464 channelID := "foo"465 gConf := genesisconfig.Load(genesisconfig.SampleSingleMSPSoloProfile, configtest.GetDevConfigDir())466 gConf.Orderer.Capabilities = map[string]bool{467 capabilities.OrdererV2_0: true,468 }469 channelGroup, err := encoder.NewChannelGroup(gConf)470 require.NoError(t, err)471 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore())472 require.NoError(t, err)473 ctxm, err := channelconfig.NewBundle(channelID, &cb.Config{ChannelGroup: channelGroup}, cryptoProvider)474 require.NoError(t, err)475 originalCG := proto.Clone(ctxm.ConfigtxValidator().ConfigProto().ChannelGroup).(*cb.ConfigGroup)476 templator := NewDefaultTemplator(&mockDefaultTemplatorSupport{477 Resources: ctxm,478 }, cryptoProvider)479 t.Run("BadPayload", func(t *testing.T) {480 _, err := templator.NewChannelConfig(&cb.Envelope{Payload: []byte("bad payload")})481 require.Error(t, err, "Should not be able to create new channel config from bad payload.")482 })483 for _, tc := range []struct {484 name string485 payload *cb.Payload486 regex string487 }{488 {489 "BadPayloadData",490 &cb.Payload{491 Data: []byte("bad payload data"),492 },493 "^Failing initial channel config creation because of config update envelope unmarshaling error:",494 },495 {496 "BadConfigUpdate",497 &cb.Payload{498 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},499 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{500 ConfigUpdate: []byte("bad config update envelope data"),501 }),502 },503 "^Failing initial channel config creation because of config update unmarshaling error:",504 },505 {506 "MismatchedChannelID",507 &cb.Payload{508 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},509 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{510 ConfigUpdate: protoutil.MarshalOrPanic(511 &cb.ConfigUpdate{512 ChannelId: "foo",513 },514 ),515 }),516 },517 "mismatched channel IDs",518 },519 {520 "EmptyConfigUpdateWriteSet",521 &cb.Payload{522 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},523 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{524 ConfigUpdate: protoutil.MarshalOrPanic(525 &cb.ConfigUpdate{},526 ),527 }),528 },529 "^Config update has an empty writeset$",530 },531 {532 "WriteSetNoGroups",533 &cb.Payload{534 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},535 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{536 ConfigUpdate: protoutil.MarshalOrPanic(537 &cb.ConfigUpdate{538 WriteSet: &cb.ConfigGroup{},539 },540 ),541 }),542 },543 "^Config update has missing application group$",544 },545 {546 "WriteSetNoApplicationGroup",547 &cb.Payload{548 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},549 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{550 ConfigUpdate: protoutil.MarshalOrPanic(551 &cb.ConfigUpdate{552 WriteSet: &cb.ConfigGroup{553 Groups: map[string]*cb.ConfigGroup{},554 },555 },556 ),557 }),558 },559 "^Config update has missing application group$",560 },561 {562 "BadWriteSetApplicationGroupVersion",563 &cb.Payload{564 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},565 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{566 ConfigUpdate: protoutil.MarshalOrPanic(567 &cb.ConfigUpdate{568 WriteSet: &cb.ConfigGroup{569 Groups: map[string]*cb.ConfigGroup{570 channelconfig.ApplicationGroupKey: {571 Version: 100,572 },573 },574 },575 },576 ),577 }),578 },579 "^Config update for channel creation does not set application group version to 1,",580 },581 {582 "MissingWriteSetConsortiumValue",583 &cb.Payload{584 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},585 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{586 ConfigUpdate: protoutil.MarshalOrPanic(587 &cb.ConfigUpdate{588 WriteSet: &cb.ConfigGroup{589 Groups: map[string]*cb.ConfigGroup{590 channelconfig.ApplicationGroupKey: {591 Version: 1,592 },593 },594 Values: map[string]*cb.ConfigValue{},595 },596 },597 ),598 }),599 },600 "^Consortium config value missing$",601 },602 {603 "BadWriteSetConsortiumValueValue",604 &cb.Payload{605 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},606 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{607 ConfigUpdate: protoutil.MarshalOrPanic(608 &cb.ConfigUpdate{609 WriteSet: &cb.ConfigGroup{610 Groups: map[string]*cb.ConfigGroup{611 channelconfig.ApplicationGroupKey: {612 Version: 1,613 },614 },615 Values: map[string]*cb.ConfigValue{616 channelconfig.ConsortiumKey: {617 Value: []byte("bad consortium value"),618 },619 },620 },621 },622 ),623 }),624 },625 "^Error reading unmarshaling consortium name:",626 },627 {628 "UnknownConsortiumName",629 &cb.Payload{630 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},631 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{632 ConfigUpdate: protoutil.MarshalOrPanic(633 &cb.ConfigUpdate{634 WriteSet: &cb.ConfigGroup{635 Groups: map[string]*cb.ConfigGroup{636 channelconfig.ApplicationGroupKey: {637 Version: 1,638 },639 },640 Values: map[string]*cb.ConfigValue{641 channelconfig.ConsortiumKey: {642 Value: protoutil.MarshalOrPanic(643 &cb.Consortium{644 Name: "NotTheNameYouAreLookingFor",645 },646 ),647 },648 },649 },650 },651 ),652 }),653 },654 "^Unknown consortium name:",655 },656 {657 "Missing consortium members",658 &cb.Payload{659 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},660 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{661 ConfigUpdate: protoutil.MarshalOrPanic(662 &cb.ConfigUpdate{663 WriteSet: &cb.ConfigGroup{664 Groups: map[string]*cb.ConfigGroup{665 channelconfig.ApplicationGroupKey: {666 Version: 1,667 },668 },669 Values: map[string]*cb.ConfigValue{670 channelconfig.ConsortiumKey: {671 Value: protoutil.MarshalOrPanic(672 &cb.Consortium{673 Name: genesisconfig.SampleConsortiumName,674 },675 ),676 },677 },678 },679 },680 ),681 }),682 },683 "Proposed configuration has no application group members, but consortium contains members",684 },685 {686 "Member not in consortium",687 &cb.Payload{688 Header: &cb.Header{ChannelHeader: protoutil.MarshalOrPanic(protoutil.MakeChannelHeader(cb.HeaderType_CONFIG_UPDATE, 0, "", epoch))},689 Data: protoutil.MarshalOrPanic(&cb.ConfigUpdateEnvelope{690 ConfigUpdate: protoutil.MarshalOrPanic(691 &cb.ConfigUpdate{692 WriteSet: &cb.ConfigGroup{693 Groups: map[string]*cb.ConfigGroup{694 channelconfig.ApplicationGroupKey: {695 Version: 1,696 Groups: map[string]*cb.ConfigGroup{697 "BadOrgName": {},698 },699 },700 },701 Values: map[string]*cb.ConfigValue{702 channelconfig.ConsortiumKey: {703 Value: protoutil.MarshalOrPanic(704 &cb.Consortium{705 Name: genesisconfig.SampleConsortiumName,...
crypto_create_transaction_constructor_test.go
Source:crypto_create_transaction_constructor_test.go
1/*-2 * â3 * Hedera Mirror Node4 * â5 * Copyright (C) 2019 - 2022 Hedera Hashgraph, LLC6 * â7 * Licensed under the Apache License, Version 2.0 (the "License");8 * you may not use this file except in compliance with the License.9 * You may obtain a copy of the License at10 *11 * http://www.apache.org/licenses/LICENSE-2.012 *13 * Unless required by applicable law or agreed to in writing, software14 * distributed under the License is distributed on an "AS IS" BASIS,15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.16 * See the License for the specific language governing permissions and17 * limitations under the License.18 * â19 */20package construction21import (22 "testing"23 "time"24 "github.com/hashgraph/hedera-mirror-node/hedera-mirror-rosetta/app/domain/types"25 "github.com/hashgraph/hedera-mirror-node/hedera-mirror-rosetta/app/interfaces"26 "github.com/hashgraph/hedera-mirror-node/hedera-mirror-rosetta/test/domain"27 "github.com/hashgraph/hedera-sdk-go/v2"28 "github.com/stretchr/testify/assert"29 "github.com/stretchr/testify/suite"30)31const (32 initialBalance = 1033 maxAutomaticTokenAssociations uint32 = 1034)35var (36 _, newAccountPublicKey = domain.GenEd25519KeyPair()37 proxyAccountId = hedera.AccountID{Account: 6000}38)39func TestCryptoCreateTransactionConstructorSuite(t *testing.T) {40 suite.Run(t, new(cryptoCreateTransactionConstructorSuite))41}42type cryptoCreateTransactionConstructorSuite struct {43 suite.Suite44}45func (suite *cryptoCreateTransactionConstructorSuite) TestNewTransactionConstructor() {46 h := newCryptoCreateTransactionConstructor()47 assert.NotNil(suite.T(), h)48}49func (suite *cryptoCreateTransactionConstructorSuite) TestGetDefaultMaxTransactionFee() {50 h := newCryptoCreateTransactionConstructor()51 assert.Equal(suite.T(), types.HbarAmount{Value: 3_00000000}, h.GetDefaultMaxTransactionFee())52}53func (suite *cryptoCreateTransactionConstructorSuite) TestGetOperationType() {54 h := newCryptoCreateTransactionConstructor()55 assert.Equal(suite.T(), types.OperationTypeCryptoCreateAccount, h.GetOperationType())56}57func (suite *cryptoCreateTransactionConstructorSuite) TestGetSdkTransactionType() {58 h := newCryptoCreateTransactionConstructor()59 assert.Equal(suite.T(), "AccountCreateTransaction", h.GetSdkTransactionType())60}61func (suite *cryptoCreateTransactionConstructorSuite) TestConstruct() {62 var tests = []struct {63 name string64 updateOperations updateOperationsFunc65 expectError bool66 }{67 {name: "Success"},68 {name: "EmptyOperations", updateOperations: getEmptyOperations, expectError: true},69 }70 for _, tt := range tests {71 suite.T().Run(tt.name, func(t *testing.T) {72 // given73 operations := getCryptoCreateOperations()74 h := newCryptoCreateTransactionConstructor()75 if tt.updateOperations != nil {76 operations = tt.updateOperations(operations)77 }78 // when79 tx, signers, err := h.Construct(defaultContext, operations)80 // then81 if tt.expectError {82 assert.NotNil(t, err)83 assert.Nil(t, signers)84 assert.Nil(t, tx)85 } else {86 assert.Nil(t, err)87 assert.ElementsMatch(t, []types.AccountId{accountIdA}, signers)88 assertCryptoCreateTransaction(t, operations[0], tx)89 }90 })91 }92}93func (suite *cryptoCreateTransactionConstructorSuite) TestParse() {94 defaultGetTransaction := func() interfaces.Transaction {95 return hedera.NewAccountCreateTransaction().96 SetAccountMemo(memo).97 SetAutoRenewPeriod(time.Second * time.Duration(autoRenewPeriod)).98 SetInitialBalance(hedera.HbarFromTinybar(initialBalance)).99 SetKey(newAccountPublicKey).100 SetMaxAutomaticTokenAssociations(maxAutomaticTokenAssociations).101 SetProxyAccountID(proxyAccountId).102 SetTransactionID(hedera.TransactionIDGenerate(sdkAccountIdA))103 }104 var tests = []struct {105 name string106 getTransaction func() interfaces.Transaction107 expectError bool108 }{109 {110 name: "Success",111 getTransaction: defaultGetTransaction,112 },113 {114 name: "InvalidTransaction",115 getTransaction: func() interfaces.Transaction {116 return hedera.NewTransferTransaction()117 },118 expectError: true,119 },120 {121 name: "KeyNotSet",122 getTransaction: func() interfaces.Transaction {123 tx := defaultGetTransaction()124 accountCreateTx, _ := tx.(*hedera.AccountCreateTransaction)125 accountCreateTx.SetKey(nil)126 return tx127 },128 expectError: true,129 },130 {131 name: "OutOfRangePayerAccountId",132 getTransaction: func() interfaces.Transaction {133 return hedera.NewAccountCreateTransaction().134 SetAccountMemo(memo).135 SetAutoRenewPeriod(time.Second * time.Duration(autoRenewPeriod)).136 SetInitialBalance(hedera.HbarFromTinybar(initialBalance)).137 SetKey(newAccountPublicKey).138 SetMaxAutomaticTokenAssociations(maxAutomaticTokenAssociations).139 SetProxyAccountID(proxyAccountId).140 SetTransactionID(hedera.TransactionIDGenerate(outOfRangeAccountId))141 },142 expectError: true,143 },144 {145 name: "TransactionIDNotSet",146 getTransaction: func() interfaces.Transaction {147 return hedera.NewAccountCreateTransaction().148 SetAccountMemo(memo).149 SetAutoRenewPeriod(time.Second * time.Duration(autoRenewPeriod)).150 SetInitialBalance(hedera.HbarFromTinybar(initialBalance)).151 SetKey(newAccountPublicKey).152 SetMaxAutomaticTokenAssociations(maxAutomaticTokenAssociations).153 SetProxyAccountID(proxyAccountId)154 },155 expectError: true,156 },157 }158 for _, tt := range tests {159 suite.T().Run(tt.name, func(t *testing.T) {160 // given161 expectedOperations := getCryptoCreateOperations()162 h := newCryptoCreateTransactionConstructor()163 tx := tt.getTransaction()164 // when165 operations, signers, err := h.Parse(defaultContext, tx)166 // then167 if tt.expectError {168 assert.NotNil(t, err)169 assert.Nil(t, operations)170 assert.Nil(t, signers)171 } else {172 assert.Nil(t, err)173 assert.ElementsMatch(t, []types.AccountId{accountIdA}, signers)174 assert.ElementsMatch(t, expectedOperations, operations)175 }176 })177 }178}179func (suite *cryptoCreateTransactionConstructorSuite) TestPreprocess() {180 var tests = []struct {181 name string182 updateOperations updateOperationsFunc183 expectError bool184 }{185 {name: "Success"},186 {187 name: "InvalidAmount",188 updateOperations: updateAmount(types.NewTokenAmount(dbTokenA, 1)),189 expectError: true,190 },191 {192 name: "InvalidMetadataKey",193 updateOperations: updateOperationMetadata("key", "key"),194 expectError: true,195 },196 {197 name: "InvalidMetadataAutoRenewPeriod",198 updateOperations: updateOperationMetadata("auto_renew_period", "x"),199 expectError: true,200 },201 {202 name: "InvalidMetadataMaxAutomaticTokenAssociations",203 updateOperations: updateOperationMetadata("max_automatic_token_associations", "xyz"),204 expectError: true,205 },206 {207 name: "InvalidMetadataMemo",208 updateOperations: updateOperationMetadata("memo", 156),209 expectError: true,210 },211 {212 name: "InvalidMetadataProxyAccountId",213 updateOperations: updateOperationMetadata("proxy_account_id", "x.y.z"),214 expectError: true,215 },216 {217 name: "MissingMetadata",218 updateOperations: getEmptyOperationMetadata,219 expectError: true,220 },221 {222 name: "MissingMetadataKey",223 updateOperations: deleteOperationMetadata("key"),224 expectError: true,225 },226 {227 name: "MultipleOperations",228 updateOperations: addOperation,229 expectError: true,230 },231 {232 name: "NegativeInitialBalance",233 updateOperations: negateAmountValue,234 expectError: true,235 },236 {237 name: "InvalidOperationType",238 updateOperations: updateOperationType(types.OperationTypeCryptoTransfer),239 expectError: true,240 },241 }242 for _, tt := range tests {243 suite.T().Run(tt.name, func(t *testing.T) {244 // given245 operations := getCryptoCreateOperations()246 h := newCryptoCreateTransactionConstructor()247 if tt.updateOperations != nil {248 operations = tt.updateOperations(operations)249 }250 // when251 signers, err := h.Preprocess(defaultContext, operations)252 // then253 if tt.expectError {254 assert.NotNil(t, err)255 assert.Nil(t, signers)256 } else {257 assert.Nil(t, err)258 assert.ElementsMatch(t, []types.AccountId{accountIdA}, signers)259 }260 })261 }262}263func assertCryptoCreateTransaction(264 t *testing.T,265 operation types.Operation,266 actual interfaces.Transaction,267) {268 assert.IsType(t, &hedera.AccountCreateTransaction{}, actual)269 assert.False(t, actual.IsFrozen())270 tx, _ := actual.(*hedera.AccountCreateTransaction)271 key, err := tx.GetKey()272 assert.NoError(t, err)273 assert.Equal(t, operation.Metadata["key"], key.String())274 assert.Equal(t, operation.Metadata["auto_renew_period"], int64(tx.GetAutoRenewPeriod().Seconds()))275 assert.Equal(t, operation.Metadata["max_automatic_token_associations"], tx.GetMaxAutomaticTokenAssociations())276 assert.Equal(t, operation.Metadata["memo"], tx.GetAccountMemo())277 assert.Equal(t, operation.Metadata["proxy_account_id"], tx.GetProxyAccountID().String())278}279func getCryptoCreateOperations() types.OperationSlice {280 operation := types.Operation{281 AccountId: accountIdA,282 Amount: &types.HbarAmount{Value: -initialBalance},283 Type: types.OperationTypeCryptoCreateAccount,284 Metadata: map[string]interface{}{285 "auto_renew_period": autoRenewPeriod,286 "key": newAccountPublicKey.String(),287 "max_automatic_token_associations": maxAutomaticTokenAssociations,288 "memo": memo,289 "proxy_account_id": proxyAccountId.String(),290 },291 }292 return types.OperationSlice{operation}293}...
usecase_test.go
Source:usecase_test.go
...57 assert.Error(t, err)58 assert.Equal(t, crypto, cryptos.Domain{})59 })60}61func TestUpdateBuyCoin(t *testing.T) {62 t.Run("Test Case 1 | CryptosGetDetail - Success - Have no coin before", func(t *testing.T) {63 setup()64 cryptoRepository.On("CryptosGetDetail", mock.Anything, mock.Anything, mock.Anything).Return(cryptos.Domain{}, nil).Once()65 cryptoRepository.On("CryptosCreate", mock.Anything, mock.Anything).Return(cryptoDomain, nil).Once()66 crypto, err := cryptoService.UpdateBuyCoin(context.Background(), cryptoDomain)67 assert.Nil(t, err)68 assert.Equal(t, crypto, cryptoDomain)69 })70 t.Run("Test Case 2 | CryptosGetDetail - Success - Have coin before", func(t *testing.T) {71 setup()72 cryptoRepository.On("CryptosGetDetail", mock.Anything, mock.Anything, mock.Anything).Return(cryptoDomain, nil).Once()73 cryptoRepository.On("CryptosUpdate", mock.Anything, mock.Anything).Return(cryptoDomain, nil).Once()74 crypto, err := cryptoService.UpdateBuyCoin(context.Background(), cryptoDomain)75 assert.Nil(t, err)76 assert.Equal(t, crypto, cryptoDomain)77 })78 t.Run("Test Case 3 | CryptosGetDetail - Success - Have coin before but error", func(t *testing.T) {79 setup()80 cryptoRepository.On("CryptosGetDetail", mock.Anything, mock.Anything, mock.Anything).Return(cryptoDomain, nil).Once()81 cryptoRepository.On("CryptosUpdate", mock.Anything, mock.Anything).Return(cryptos.Domain{}, businesses.ErrForTest).Once()82 crypto, err := cryptoService.UpdateBuyCoin(context.Background(), cryptoDomain)83 assert.Error(t, err)84 assert.Equal(t, crypto, cryptos.Domain{})85 })86 t.Run("Test Case 4 | CryptosGetDetail - Success - Have coin before but error", func(t *testing.T) {87 setup()88 cryptoRepository.On("CryptosGetDetail", mock.Anything, mock.Anything, mock.Anything).Return(cryptos.Domain{}, nil).Once()89 cryptoRepository.On("CryptosCreate", mock.Anything, mock.Anything).Return(cryptos.Domain{}, businesses.ErrForTest).Once()90 crypto, err := cryptoService.UpdateBuyCoin(context.Background(), cryptoDomain)91 assert.Error(t, err)92 assert.Equal(t, crypto, cryptos.Domain{})93 })94}95func TestUpdateSellCoin(t *testing.T) {96 t.Run("Test Case 1 | UpdateSellCoin - Success", func(t *testing.T) {97 setup()98 cryptoRepository.On("CryptosGetDetail", mock.Anything, mock.Anything, mock.Anything).Return(cryptoDomain, nil).Once()99 cryptoRepository.On("CryptosUpdate", mock.Anything, mock.Anything).Return(cryptoDomain, nil).Once()100 crypto, err := cryptoService.UpdateSellCoin(context.Background(), cryptoDomain)101 assert.Nil(t, err)102 assert.Equal(t, crypto, cryptoDomain)103 })104 t.Run("Test Case 2 | UpdateSellCoin - Error", func(t *testing.T) {105 setup()106 cryptoRepository.On("CryptosGetDetail", mock.Anything, mock.Anything, mock.Anything).Return(cryptoDomain, nil).Once()107 cryptoRepository.On("CryptosUpdate", mock.Anything, mock.Anything).Return(cryptos.Domain{}, businesses.ErrForTest).Once()108 crypto, err := cryptoService.UpdateSellCoin(context.Background(), cryptoDomain)109 assert.Error(t, err)110 assert.Equal(t, crypto, cryptos.Domain{})111 })112}...
Update
Using AI Code Generation
1import (2type SimpleChaincode struct {3}4func main() {5 err := shim.Start(new(SimpleChaincode))6 if err != nil {7 fmt.Printf("Error starting Simple chaincode: %s", err)8 }9}10func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {11 return shim.Success(nil)12}13func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {14 function, args := stub.GetFunctionAndParameters()15 if function == "invoke" {16 return t.invoke(stub, args)17 }18 return shim.Error("Invalid invoke function name. Expecting \"invoke\"")19}20func (t *SimpleChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response {21 fmt.Println("running invoke()")22 if len(args) != 2 {23 return shim.Error("Incorrect number of arguments. Expecting 2. name of the key and value to set")24 }25 err = stub.PutState(key, []byte(value))26 if err != nil {27 return shim.Error(err.Error())28 }29 return shim.Success(nil)30}31import (32type SimpleChaincode struct {33}34func main() {35 err := shim.Start(new(SimpleChaincode))36 if err != nil {37 fmt.Printf("Error starting Simple chaincode: %s", err)38 }39}40func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {41 return shim.Success(nil)42}43func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {44 function, args := stub.GetFunctionAndParameters()45 if function == "invoke" {46 return t.invoke(stub, args)47 }48 return shim.Error("Invalid invoke function name. Expecting \"invoke\"")49}50func (t *SimpleChaincode) invoke(stub shim
Update
Using AI Code Generation
1import "fmt"2func main() {3 data := []byte("Hello world!")4 fmt.Printf("%x5 h := crypto.SHA256.New()6 h.Write(data)7 bs := h.Sum(nil)8 fmt.Printf("%x9}10import (11func main() {12 key := []byte("example key 1234")13 c, err := aes.NewCipher(key)
Update
Using AI Code Generation
1import "fmt"2import "crypto"3import "crypto/rand"4import "crypto/rsa"5import "crypto/sha256"6import "encoding/base64"7func main() {8 privateKey, err := rsa.GenerateKey(rand.Reader, 2048)9 if err != nil {10 fmt.Println(err)11 }12 message := []byte("Hello World")13 messageHash := sha256.Sum256(message)14 signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, messageHash[:])15 if err != nil {16 fmt.Println(err)17 }18 err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, messageHash[:], signature)19 if err != nil {20 fmt.Println("Who are you?")21 }22 fmt.Println("Signature Verified")23}24import "fmt"25import "crypto"26import "crypto/rand"27import "crypto/rsa"28import "crypto/sha256"29import "encoding/base64"30func main() {31 privateKey, err := rsa.GenerateKey(rand.Reader, 2048)32 if err != nil {33 fmt.Println(err)34 }35 message := []byte("Hello World")36 messageHash := sha256.Sum256(message)37 signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, messageHash[:])38 if err != nil {39 fmt.Println(err)40 }41 err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, messageHash[:], signature)42 if err != nil {43 fmt.Println("Who are you?")44 }45 fmt.Println("Signature Verified")46}
Update
Using AI Code Generation
1import (2func main() {3 privateKey, err := rsa.GenerateKey(rand.Reader, 2048)4 if err != nil {5 fmt.Println(err.Error())6 }7 opts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthAuto, Hash: crypto.SHA256}8 hashed := sha256.Sum256([]byte("Hello World"))9 signature, err := rsa.SignPSS(rand.Reader, privateKey, crypto.SHA256, hashed[:], opts)10 if err != nil {11 fmt.Println(err.Error())12 }13 err = rsa.VerifyPSS(&privateKey.PublicKey, crypto.SHA256, hashed[:], signature, opts)14 if err != nil {15 fmt.Println("Who are you?")16 }17 fmt.Println("Welcome!")18}19import (20func main() {21 privateKey, err := rsa.GenerateKey(rand.Reader, 2048)22 if err != nil {23 fmt.Println(err.Error())24 }25 opts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthAuto, Hash: crypto.SHA256}26 hashed := sha256.Sum256([]byte("Hello World"))27 signature, err := rsa.SignPSS(rand.Reader, privateKey, crypto.SHA256, hashed[:], opts)28 if err != nil {29 fmt.Println(err.Error())30 }31 fmt.Printf("%x", signature)32}
Update
Using AI Code Generation
1func main() {2 crypto := new(Crypto)3 file, err := os.Open("test.txt")4 if err != nil {5 log.Fatal(err)6 }7 defer file.Close()8 file2, err := os.OpenFile("test2.txt", os.O_RDWR|os.O_CREATE, 0755)9 if err != nil {10 log.Fatal(err)11 }12 defer file2.Close()13 err = crypto.Update(file, file2)14 if err != nil {15 log.Fatal(err)16 }17}18func main() {19 crypto := new(Crypto)20 file, err := os.Open("test2.txt")21 if err != nil {22 log.Fatal(err)23 }24 defer file.Close()25 file2, err := os.OpenFile("test3.txt", os.O_RDWR|os.O_CREATE, 0755)26 if err != nil {27 log.Fatal(err)28 }29 defer file2.Close()30 err = crypto.Update(file, file2)31 if err != nil {32 log.Fatal(err)33 }34}35func main() {36 crypto := new(Crypto)37 file, err := os.Open("test3.txt")38 if err != nil {39 log.Fatal(err)40 }41 defer file.Close()42 file2, err := os.OpenFile("test4.txt", os.O_RDWR|os.O_CREATE, 0755)43 if err != nil {44 log.Fatal(err)45 }46 defer file2.Close()47 err = crypto.Update(file, file2)48 if err != nil {49 log.Fatal(err)50 }51}52func main() {53 crypto := new(Crypto)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!